waft-widgets 0.13.0

Widget framework and widgets for Waft
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
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
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
//! Flutter counterpart: `widgets/overscroll_indicator.dart`.
//!
//! The glow and the stretch each answer an overscroll with a confirmation
//! [`OverscrollIndicatorNotification`] dispatched on every `OverscrollNotification`: Dart's
//! guards, `_lastNotificationType is! OverscrollNotification` and
//! `_lastNotification.runtimeType is! OverscrollNotification`, test a `Type`, which is never
//! an `OverscrollNotification`, so they always hold. Keep it so until Flutter changes it, or a
//! listener's answers drift from Flutter's.

use std::cell::Cell;
use std::fmt::{self, Debug};
use std::rc::Rc;
use std::time::Duration;

use waft_animation::{
    Animation, AnimationBehavior, AnimationController, AnimationRef, AnimationStatus,
    AnimationStatusListener, AnyAnimation, CurvedAnimation, Curves, Drive, Tween,
};
use waft_embedder::{Canvas, Clip, ClipOp, Color, Offset, Paint, Rect, Size, clamp_double};
use waft_foundation::{
    App, ChangeNotifier, ChangeNotifierData, DiagnosticPropertiesBuilder, EnumProperty, Handle,
    Listenable, ListenableObject, Listener, MessageProperty, OptionRetained, Timer, ValueNotifier,
};
use waft_painting::{Axis, AxisDirection, ColorProperty, axis_direction_to_axis};
use waft_physics::{Simulation, SpringDescription, SpringSimulation, Tolerance, near_equal};
use waft_rendering::{
    CustomPainter, GrowthDirection, TickerProviderRef, apply_growth_direction_to_axis_direction,
};
use waft_scheduler::{FrameCallback, Ticker, TickerCallback, TickerProvider, TickerProviderObject};

use crate::framework::{
    BuildContext, IntoWidget, KeyRef, Notification, State, StateData, StatefulWidget, WidgetRef,
};
use crate::widgets::basic::{ClipRect, CustomPaint, RepaintBoundary, SizedBox};
use crate::widgets::media_query::MediaQuery;
use crate::widgets::notification_listener::NotificationListener;
use crate::widgets::scroll_notification::{
    OverscrollNotification, ScrollEndNotification, ScrollNotification, ScrollNotificationPredicate,
    ScrollStartNotification, ScrollUpdateNotification, ViewportNotificationData,
    ViewportNotificationMixin, default_scroll_notification_predicate,
};
use crate::widgets::stretch_effect::StretchEffect;
use crate::widgets::ticker_provider::{TickerProviderStateMixin, TickerProviderStateMixinData};
use crate::widgets::transitions::AnimatedBuilder;
use waft_foundation::Ref;

/// A visual indication that a scroll view has overscrolled.
///
/// A [`GlowingOverscrollIndicator`] listens for [`ScrollNotification`]s in order
/// to control the overscroll indication. These notifications are typically
/// generated by a `ScrollView`, such as a `ListView` or a `GridView`.
///
/// [`GlowingOverscrollIndicator`] generates [`OverscrollIndicatorNotification`]
/// before showing an overscroll indication. To prevent the indicator from
/// showing the indication, call
/// [`OverscrollIndicatorNotification::disallow_indicator`] on the notification.
///
/// Created automatically by `ScrollBehavior::build_overscroll_indicator` on platforms
/// (e.g., Android) that commonly use this type of overscroll indication.
///
/// In a `MaterialApp`, the edge glow color is the overall theme's
/// `ColorScheme.secondary` color.
///
/// ## Customizing the Glow Position for Advanced Scroll Views
///
/// When building a `CustomScrollView` with a [`GlowingOverscrollIndicator`], the
/// indicator will apply to the entire scrollable area, regardless of what
/// slivers the CustomScrollView contains.
///
/// For example, if your CustomScrollView contains a SliverAppBar in the first
/// position, the GlowingOverscrollIndicator will overlay the SliverAppBar. To
/// manipulate the position of the GlowingOverscrollIndicator in this case,
/// you can either make use of a [`NotificationListener`] and provide a
/// [`OverscrollIndicatorNotification::paint_offset`] to the
/// notification, or use a `NestedScrollView`.
///
/// See also:
///
///  * [`OverscrollIndicatorNotification`], which can be used to manipulate the
///    glow position or prevent the glow from being painted at all.
///  * [`NotificationListener`], to listen for the
///    [`OverscrollIndicatorNotification`].
///  * [`StretchingOverscrollIndicator`], a Material Design overscroll indicator.
pub struct GlowingOverscrollIndicator {
    pub key: Option<KeyRef>,

    /// Whether to show the overscroll glow on the side with negative scroll
    /// offsets.
    ///
    /// For a vertical downwards viewport, this is the top side.
    ///
    /// Defaults to true.
    ///
    /// See [`show_trailing`](Self::show_trailing) for the corresponding control on the other
    /// side of the viewport.
    pub show_leading: bool,

    /// Whether to show the overscroll glow on the side with positive scroll
    /// offsets.
    ///
    /// For a vertical downwards viewport, this is the bottom side.
    ///
    /// Defaults to true.
    ///
    /// See [`show_leading`](Self::show_leading) for the corresponding control on the other
    /// side of the viewport.
    pub show_trailing: bool,

    /// The direction of positive scroll offsets in the `Scrollable` whose
    /// overscrolls are to be visualized.
    pub axis_direction: AxisDirection,

    /// The color of the glow. The alpha channel is ignored.
    pub color: Color,

    /// A check that specifies whether a [`ScrollNotification`] should be
    /// handled by this widget.
    ///
    /// By default, checks whether `notification.depth() == 0`. Set it to something
    /// else for more complicated layouts, such as nested `ScrollView`s.
    pub notification_predicate: ScrollNotificationPredicate,

    /// The widget below this widget in the tree.
    ///
    /// The overscroll indicator will paint on top of this child. This child (and its
    /// subtree) should include a source of [`ScrollNotification`] notifications.
    ///
    /// Typically a [`GlowingOverscrollIndicator`] is created by a
    /// `ScrollBehavior::build_overscroll_indicator` method, in which case
    /// the child is usually the one provided as an argument to that method.
    pub child: Option<WidgetRef>,
}

impl GlowingOverscrollIndicator {
    /// Creates a visual indication that a scroll view has overscrolled.
    ///
    /// In order for this widget to display an overscroll indication, the [`child`](Self::child)
    /// widget must contain a widget that generates a [`ScrollNotification`], such
    /// as a `ListView` or a `GridView`.
    pub fn new(axis_direction: AxisDirection, color: Color) -> GlowingOverscrollIndicator {
        GlowingOverscrollIndicator {
            key: None,
            show_leading: true,
            show_trailing: true,
            axis_direction,
            color,
            notification_predicate: Rc::new(default_scroll_notification_predicate),
            child: None,
        }
    }

    /// Dart `GlowingOverscrollIndicator(key:)`.
    pub fn key(mut self, key: KeyRef) -> GlowingOverscrollIndicator {
        self.key = Some(key);
        self
    }

    /// Dart `GlowingOverscrollIndicator(showLeading:)`.
    pub fn show_leading(mut self, show_leading: bool) -> GlowingOverscrollIndicator {
        self.show_leading = show_leading;
        self
    }

    /// Dart `GlowingOverscrollIndicator(showTrailing:)`.
    pub fn show_trailing(mut self, show_trailing: bool) -> GlowingOverscrollIndicator {
        self.show_trailing = show_trailing;
        self
    }

    /// Dart `GlowingOverscrollIndicator(notificationPredicate:)`.
    pub fn notification_predicate(
        mut self,
        notification_predicate: ScrollNotificationPredicate,
    ) -> GlowingOverscrollIndicator {
        self.notification_predicate = notification_predicate;
        self
    }

    /// Dart `GlowingOverscrollIndicator(child:)`.
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> GlowingOverscrollIndicator {
        self.child = Some(child.into_widget());
        self
    }

    /// The axis along which scrolling occurs in the `Scrollable` whose
    /// overscrolls are to be visualized.
    pub fn axis(&self) -> Axis {
        axis_direction_to_axis(self.axis_direction)
    }
}

impl Debug for GlowingOverscrollIndicator {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let show_description = match (self.show_leading, self.show_trailing) {
            (true, true) => "both sides",
            (true, false) => "leading side only",
            (false, true) => "trailing side only",
            (false, false) => "neither side (!)",
        };
        f.debug_struct("GlowingOverscrollIndicator")
            .field("axisDirection", &self.axis_direction)
            .field("show", &show_description)
            .field("color", &self.color)
            .finish_non_exhaustive()
    }
}

impl StatefulWidget for GlowingOverscrollIndicator {
    type State = GlowingOverscrollIndicatorState;

    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
        properties.add(EnumProperty::new("axisDirection", self.axis_direction));
        let show_description = match (self.show_leading, self.show_trailing) {
            (true, true) => "both sides",
            (true, false) => "leading side only",
            (false, true) => "trailing side only",
            (false, false) => "neither side (!)",
        };
        properties.add(MessageProperty::new("show", show_description));
        properties.add(ColorProperty::new("color", self.color).with_show_name(false));
    }

    fn create_state(&self) -> GlowingOverscrollIndicatorState {
        GlowingOverscrollIndicatorState {
            state: StateData::new(),
            ticker_provider: TickerProviderStateMixinData::new(),
            leading_controller: None,
            trailing_controller: None,
            leading_and_trailing_listener: None,
            accepted: [true, true],
        }
    }
}

/// Dart's `_GlowingOverscrollIndicatorState`.
pub struct GlowingOverscrollIndicatorState {
    state: StateData<GlowingOverscrollIndicator>,
    ticker_provider: TickerProviderStateMixinData,
    leading_controller: Option<Ref<GlowController>>,
    trailing_controller: Option<Ref<GlowController>>,
    leading_and_trailing_listener: Option<Rc<dyn Listenable>>,
    /// Dart's `Map<bool, bool> _accepted`, indexed by `is_leading as usize`.
    accepted: [bool; 2],
}

impl GlowingOverscrollIndicatorState {
    fn leading_controller(self: Handle<Self>, app: &App) -> Handle<GlowController> {
        app.get(self)
            .leading_controller
            .handle()
            .expect("the controllers are made in init_state")
    }

    fn trailing_controller(self: Handle<Self>, app: &App) -> Handle<GlowController> {
        app.get(self)
            .trailing_controller
            .handle()
            .expect("the controllers are made in init_state")
    }

    fn handle_scroll_notification(
        self: Handle<Self>,
        app: &mut App,
        notification: &dyn ScrollNotification,
    ) -> bool {
        let widget = self.widget(app);
        let notification_predicate = Rc::clone(&widget.notification_predicate);
        let axis = widget.axis();
        if !notification_predicate(notification) {
            return false;
        }
        let metrics = Rc::clone(notification.metrics());
        if metrics.axis() != axis {
            // This widget is explicitly configured to one axis. If a notification
            // from a different axis bubbles up, do nothing.
            return false;
        }

        let leading_controller = self.leading_controller(app);
        let trailing_controller = self.trailing_controller(app);

        // Update the paint offset with the current scroll position. This makes
        // sure that the glow effect correctly scrolls in line with the current
        // scroll, e.g. when scrolling in the opposite direction again to hide
        // the glow. Otherwise, the glow would always stay in a fixed position,
        // even if the top of the content already scrolled away.
        // For example (CustomScrollView with sliver before center), the scroll
        // extent is [-200.0, 300.0], scroll in the opposite direction with 10.0 pixels
        // before glow disappears, so the current pixels is -190.0,
        // in this case, we should move the glow up 10.0 pixels and should not
        // overflow the scrollable widget's edge. https://github.com/flutter/flutter/issues/64149.
        let leading = app.get_mut(leading_controller);
        leading.paint_offset_scroll_pixels = -f64::min(
            metrics.pixels() - metrics.min_scroll_extent(),
            leading.paint_offset,
        );
        let trailing = app.get_mut(trailing_controller);
        trailing.paint_offset_scroll_pixels = -f64::min(
            metrics.max_scroll_extent() - metrics.pixels(),
            trailing.paint_offset,
        );

        let any = notification.as_any();
        if let Some(notification) = any.downcast_ref::<OverscrollNotification>() {
            let controller = if notification.overscroll < 0.0 {
                Some(leading_controller)
            } else if notification.overscroll > 0.0 {
                Some(trailing_controller)
            } else {
                debug_assert!(false);
                None
            };
            let is_leading = controller == Some(leading_controller);
            // Dart's `_lastNotificationType is! OverscrollNotification` (see the module doc).
            let confirmation_notification = OverscrollIndicatorNotification::new(is_leading);
            confirmation_notification.dispatch(app, Some(self.context(app)));
            let accepted = confirmation_notification.accepted.get();
            app.get_mut(self).accepted[is_leading as usize] = accepted;
            if accepted {
                let controller = controller.expect("an overscroll is on one side");
                app.get_mut(controller).paint_offset = confirmation_notification.paint_offset.get();
            }
            debug_assert!(controller.is_some());
            if app.get(self).accepted[is_leading as usize] {
                let controller = controller.expect("an overscroll is on one side");
                if notification.velocity != 0.0 {
                    debug_assert!(notification.drag_details.is_none());
                    controller.absorb_impact(app, notification.velocity.abs());
                } else {
                    debug_assert!(notification.overscroll != 0.0);
                    if let Some(drag_details) = &notification.drag_details {
                        let renderer = notification
                            .context()
                            .expect("a scroll notification carries the scrollable's context")
                            .find_render_object(app)
                            .expect("the scrollable has a render object")
                            .as_box()
                            .expect("the scrollable's render object is a box");
                        debug_assert!(renderer.has_size(app));
                        let size = renderer.size(app);
                        let position =
                            renderer.global_to_local(app, drag_details.global_position, None);
                        match notification.metrics().axis() {
                            Axis::Horizontal => controller.pull(
                                app,
                                notification.overscroll.abs(),
                                size.width(),
                                clamp_double(position.dy(), 0.0, size.height()),
                                size.height(),
                            ),
                            Axis::Vertical => controller.pull(
                                app,
                                notification.overscroll.abs(),
                                size.height(),
                                clamp_double(position.dx(), 0.0, size.width()),
                                size.width(),
                            ),
                        }
                    }
                }
            }
        } else if any
            .downcast_ref::<ScrollEndNotification>()
            .is_some_and(|notification| notification.drag_details.is_some())
            || any
                .downcast_ref::<ScrollUpdateNotification>()
                .is_some_and(|notification| notification.drag_details.is_some())
        {
            leading_controller.scroll_end(app);
            trailing_controller.scroll_end(app);
        }
        false
    }
}

impl Debug for GlowingOverscrollIndicatorState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("GlowingOverscrollIndicatorState")
            .finish_non_exhaustive()
    }
}

impl TickerProviderStateMixin for GlowingOverscrollIndicatorState {
    fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
        &app.get(self).ticker_provider
    }

    fn ticker_provider_data_mut(
        self: Handle<Self>,
        app: &mut App,
    ) -> &mut TickerProviderStateMixinData {
        &mut app.get_mut(self).ticker_provider
    }
}

impl TickerProviderObject for GlowingOverscrollIndicatorState {
    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
        TickerProviderStateMixin::create_ticker(self, app, on_tick)
    }
}

impl State for GlowingOverscrollIndicatorState {
    type Widget = GlowingOverscrollIndicator;
    crate::state_accessors!();

    fn init_state(self: Handle<Self>, app: &mut App) {
        let widget = self.widget(app);
        let (color, axis) = (widget.color, widget.axis());
        let leading_controller =
            GlowController::new(app, TickerProviderRef::new(self), color, axis);
        let trailing_controller =
            GlowController::new(app, TickerProviderRef::new(self), color, axis);
        let listener: Rc<dyn Listenable> = Rc::new(waft_foundation::MergingListenable::new(vec![
            Some(Rc::new(leading_controller.clone())),
            Some(Rc::new(trailing_controller.clone())),
        ]));
        let state = app.get_mut(self);
        state.leading_controller = Some(leading_controller);
        state.trailing_controller = Some(trailing_controller);
        state.leading_and_trailing_listener = Some(listener);
    }

    fn did_update_widget(
        self: Handle<Self>,
        app: &mut App,
        old_widget: &GlowingOverscrollIndicator,
    ) {
        let widget = self.widget(app);
        let (color, axis) = (widget.color, widget.axis());
        if old_widget.color != color || old_widget.axis() != axis {
            let leading_controller = self.leading_controller(app);
            let trailing_controller = self.trailing_controller(app);
            leading_controller.set_color(app, color);
            leading_controller.set_axis(app, axis);
            trailing_controller.set_color(app, color);
            trailing_controller.set_axis(app, axis);
        }
    }

    fn activate(self: Handle<Self>, app: &mut App) {
        TickerProviderStateMixin::activate(self, app);
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        self.leading_controller(app).dispose(app);
        self.trailing_controller(app).dispose(app);
        TickerProviderStateMixin::dispose(self, app);
    }

    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
        let widget = self.widget(app);
        let state = app.get(self);
        let painter = GlowingOverscrollIndicatorPainter {
            leading_controller: if widget.show_leading {
                state.leading_controller.clone()
            } else {
                None
            },
            trailing_controller: if widget.show_trailing {
                state.trailing_controller.clone()
            } else {
                None
            },
            axis_direction: widget.axis_direction,
            repaint: state.leading_and_trailing_listener.clone(),
        };
        let mut child_boundary = RepaintBoundary::new();
        if let Some(child) = widget.child.clone() {
            child_boundary = child_boundary.child(child);
        }
        NotificationListener::<dyn ScrollNotification>::new(
            RepaintBoundary::new().child(
                CustomPaint::new()
                    .foreground_painter(painter)
                    .child(child_boundary),
            ),
        )
        .on_notification(
            move |app: &mut App, notification: &dyn ScrollNotification| {
                self.handle_scroll_notification(app, notification)
            },
        )
        .into_widget()
    }
}

// The Glow logic is a port of the logic in the following file:
// https://android.googlesource.com/platform/frameworks/base/+/main/core/java/android/widget/EdgeEffect.java
// as of December 2016.

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum GlowState {
    Idle,
    Absorb,
    Pull,
    Recede,
}

/// Dart's `_GlowController`.
///
/// The fields Dart declares `late final` and builds after its status listener is on the glow
/// controller are `Option`s here, set in [`new`](Self::new) in Dart's order, so the status
/// listeners run in Dart's order.
struct GlowController {
    change_notifier: ChangeNotifierData,

    // animation of the main axis direction
    state: GlowState,
    glow_controller: Ref<AnimationController>,
    pull_recede_timer: Option<Timer>,
    paint_offset: f64,
    paint_offset_scroll_pixels: f64,

    // animation values
    decelerator: Option<Ref<CurvedAnimation>>,
    glow_opacity_tween: Ref<Tween<f64>>,
    glow_opacity: Option<AnimationRef<f64>>,
    glow_size_tween: Ref<Tween<f64>>,
    glow_size: Option<AnimationRef<f64>>,

    // animation of the cross axis position
    displacement_ticker: Option<Ref<Ticker>>,
    displacement_ticker_last_elapsed: Option<Duration>,
    displacement_target: f64,
    displacement: f64,

    // tracking the pull distance
    pull_distance: f64,

    color: Color,
    axis: Axis,
}

impl GlowController {
    const RECEDE_TIME: Duration = Duration::from_millis(600);
    const PULL_TIME: Duration = Duration::from_millis(167);
    const PULL_HOLD_TIME: Duration = Duration::from_millis(167);
    const PULL_DECAY_TIME: Duration = Duration::from_millis(2000);

    const MAX_OPACITY: f64 = 0.5;
    const PULL_OPACITY_GLOW_FACTOR: f64 = 0.8;
    const VELOCITY_GLOW_FACTOR: f64 = 0.00006;
    const SQRT3: f64 = 1.73205080757; // const math.sqrt(3)
    const WIDTH_TO_HEIGHT_FACTOR: f64 = (3.0 / 4.0) * (2.0 - GlowController::SQRT3);

    // absorbed velocities are clamped to the range MIN_VELOCITY..MAX_VELOCITY
    const MIN_VELOCITY: f64 = 100.0; // logical pixels per second
    const MAX_VELOCITY: f64 = 10000.0; // logical pixels per second

    /// Dart's `static final _crossAxisHalfTime`, a sixtieth of a second rounded to the
    /// microsecond.
    fn cross_axis_half_time() -> Duration {
        Duration::from_micros((1_000_000.0_f64 / 60.0).round() as u64)
    }

    fn new(
        app: &mut App,
        vsync: TickerProviderRef,
        color: Color,
        axis: Axis,
    ) -> Ref<GlowController> {
        let glow_controller = AnimationController::new(
            app,
            None,
            None,
            None,
            0.0,
            1.0,
            AnimationBehavior::Normal,
            vsync.clone(),
        );
        let glow_opacity_tween = Tween::new(app, Some(0.0), Some(0.0));
        let glow_size_tween = Tween::new(app, Some(0.0), Some(0.0));
        let this = app.create(GlowController {
            change_notifier: ChangeNotifierData::new(),
            state: GlowState::Idle,
            glow_controller: glow_controller.clone(),
            pull_recede_timer: None,
            paint_offset: 0.0,
            paint_offset_scroll_pixels: 0.0,
            decelerator: None,
            glow_opacity_tween: glow_opacity_tween.clone(),
            glow_opacity: None,
            glow_size_tween: glow_size_tween.clone(),
            glow_size: None,
            displacement_ticker: None,
            displacement_ticker_last_elapsed: None,
            displacement_target: 0.5,
            displacement: 0.5,
            pull_distance: 0.0,
            color,
            axis,
        });
        let handle = this.handle();
        glow_controller.view().add_status_listener(
            app,
            AnimationStatusListener::handle_method(handle, GlowController::change_phase),
        );
        let decelerator =
            CurvedAnimation::new(app, glow_controller.erase(), Curves::decelerate(), None);
        decelerator.add_listener(
            app,
            Listener::handle_method(handle, Handle::<GlowController>::notify_listeners),
        );
        let glow_opacity = decelerator.drive(app, glow_opacity_tween);
        let glow_size = decelerator.drive(app, glow_size_tween);
        let displacement_ticker = vsync.create_ticker(
            app,
            FrameCallback::handle_method(handle, GlowController::tick_displacement),
        );
        let controller = app.get_mut(&this);
        controller.decelerator = Some(decelerator);
        controller.glow_opacity = Some(glow_opacity);
        controller.glow_size = Some(glow_size);
        controller.displacement_ticker = Some(displacement_ticker);
        this
    }

    fn decelerator(self: Handle<Self>, app: &App) -> Handle<CurvedAnimation> {
        app.get(self)
            .decelerator
            .handle()
            .expect("set by the constructor")
    }

    fn glow_opacity(self: Handle<Self>, app: &App) -> AnyAnimation<f64> {
        app.get(self)
            .glow_opacity
            .handle()
            .expect("set by the constructor")
    }

    fn glow_size(self: Handle<Self>, app: &App) -> AnyAnimation<f64> {
        app.get(self)
            .glow_size
            .handle()
            .expect("set by the constructor")
    }

    fn displacement_ticker(self: Handle<Self>, app: &App) -> Handle<Ticker> {
        app.get(self)
            .displacement_ticker
            .handle()
            .expect("set by the constructor")
    }

    fn color(self: Handle<Self>, app: &App) -> Color {
        app.get(self).color
    }

    fn set_color(self: Handle<Self>, app: &mut App, value: Color) {
        if self.color(app) == value {
            return;
        }
        app.get_mut(self).color = value;
        self.notify_listeners(app);
    }

    fn axis(self: Handle<Self>, app: &App) -> Axis {
        app.get(self).axis
    }

    fn set_axis(self: Handle<Self>, app: &mut App, value: Axis) {
        if self.axis(app) == value {
            return;
        }
        app.get_mut(self).axis = value;
        self.notify_listeners(app);
    }

    fn cancel_pull_recede_timer(self: Handle<Self>, app: &mut App) {
        if let Some(timer) = app.get(self).pull_recede_timer {
            timer.cancel(app);
        }
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        app.get(self).glow_controller.dispose(app);
        self.decelerator(app).dispose(app);
        self.displacement_ticker(app).dispose(app);
        self.cancel_pull_recede_timer(app);
        ChangeNotifierData::dispose(app, self);
    }

    /// Handle a scroll slamming into the edge at a particular velocity.
    ///
    /// The velocity must be positive.
    fn absorb_impact(self: Handle<Self>, app: &mut App, velocity: f64) {
        debug_assert!(velocity >= 0.0);
        self.cancel_pull_recede_timer(app);
        app.get_mut(self).pull_recede_timer = None;
        let velocity = clamp_double(velocity, Self::MIN_VELOCITY, Self::MAX_VELOCITY);
        let glow_opacity_begin = if app.get(self).state == GlowState::Idle {
            0.3
        } else {
            self.glow_opacity(app).value(app)
        };
        let glow_opacity_tween = app.get(self).glow_opacity_tween.handle();
        glow_opacity_tween.set_begin(app, Some(glow_opacity_begin));
        glow_opacity_tween.set_end(
            app,
            Some(clamp_double(
                velocity * Self::VELOCITY_GLOW_FACTOR,
                glow_opacity_begin,
                Self::MAX_OPACITY,
            )),
        );
        let glow_size_tween = app.get(self).glow_size_tween.handle();
        let glow_size = self.glow_size(app).value(app);
        glow_size_tween.set_begin(app, Some(glow_size));
        glow_size_tween.set_end(
            app,
            Some(f64::min(0.025 + 7.5e-7 * velocity * velocity, 1.0)),
        );
        let glow_controller = app.get(self).glow_controller.handle();
        app.get_mut(glow_controller).duration = Some(Duration::from_millis(
            (0.15 + velocity * 0.02).round() as u64,
        ));
        glow_controller.forward(app, Some(0.0));
        let controller = app.get_mut(self);
        controller.displacement = 0.5;
        controller.state = GlowState::Absorb;
    }

    /// Handle a user-driven overscroll.
    ///
    /// The `overscroll` argument should be the scroll distance in logical pixels,
    /// the `extent` argument should be the total dimension of the viewport in the
    /// main axis in logical pixels, the `cross_axis_offset` argument should be the
    /// distance from the leading (left or top) edge of the cross axis of the
    /// viewport, and the `cross_extent` should be the size of the cross axis. For
    /// example, a pull of 50 pixels up the middle of a 200 pixel high and 100
    /// pixel wide vertical viewport should result in a call of `pull(50.0, 200.0,
    /// 50.0, 100.0)`. The `overscroll` value should be positive regardless of the
    /// direction.
    fn pull(
        self: Handle<Self>,
        app: &mut App,
        overscroll: f64,
        extent: f64,
        cross_axis_offset: f64,
        cross_extent: f64,
    ) {
        self.cancel_pull_recede_timer(app);
        // This factor is magic. Not clear why we need it to match Android.
        app.get_mut(self).pull_distance += overscroll / 200.0;
        // Dart reads each animation's value again once its tween's `begin` is set, and the
        // second read sees the new `begin`.
        let glow_opacity_tween = app.get(self).glow_opacity_tween.handle();
        let glow_opacity = self.glow_opacity(app).value(app);
        glow_opacity_tween.set_begin(app, Some(glow_opacity));
        let glow_opacity = self.glow_opacity(app).value(app);
        glow_opacity_tween.set_end(
            app,
            Some(f64::min(
                glow_opacity + overscroll / extent * Self::PULL_OPACITY_GLOW_FACTOR,
                Self::MAX_OPACITY,
            )),
        );
        let height = f64::min(extent, cross_extent * Self::WIDTH_TO_HEIGHT_FACTOR);
        let glow_size_tween = app.get(self).glow_size_tween.handle();
        let glow_size = self.glow_size(app).value(app);
        glow_size_tween.set_begin(app, Some(glow_size));
        let pull_distance = app.get(self).pull_distance;
        let glow_size = self.glow_size(app).value(app);
        glow_size_tween.set_end(
            app,
            Some(f64::max(
                1.0 - 1.0 / (0.7 * (pull_distance * height).sqrt()),
                glow_size,
            )),
        );
        app.get_mut(self).displacement_target = cross_axis_offset / cross_extent;
        let displacement_ticker = self.displacement_ticker(app);
        let controller = app.get(self);
        if controller.displacement_target != controller.displacement {
            if !displacement_ticker.is_ticking(app) {
                debug_assert!(app.get(self).displacement_ticker_last_elapsed.is_none());
                displacement_ticker.start(app);
            }
        } else {
            displacement_ticker.stop(app, false);
            app.get_mut(self).displacement_ticker_last_elapsed = None;
        }
        let glow_controller = app.get(self).glow_controller.handle();
        app.get_mut(glow_controller).duration = Some(Self::PULL_TIME);
        if app.get(self).state != GlowState::Pull {
            glow_controller.forward(app, Some(0.0));
            app.get_mut(self).state = GlowState::Pull;
        } else if !glow_controller.is_animating(app) {
            debug_assert!(glow_controller.value(app) == 1.0);
            self.notify_listeners(app);
        }
        let timer = Timer::new(
            app,
            Self::PULL_HOLD_TIME,
            Listener::new(move |app: &mut App| self.recede(app, Self::PULL_DECAY_TIME)),
        );
        app.get_mut(self).pull_recede_timer = Some(timer);
    }

    fn scroll_end(self: Handle<Self>, app: &mut App) {
        if app.get(self).state == GlowState::Pull {
            self.recede(app, Self::RECEDE_TIME);
        }
    }

    fn change_phase(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
        if !status.is_completed() {
            return;
        }
        match app.get(self).state {
            GlowState::Absorb => self.recede(app, Self::RECEDE_TIME),
            GlowState::Recede => {
                let controller = app.get_mut(self);
                controller.state = GlowState::Idle;
                controller.pull_distance = 0.0;
            }
            GlowState::Pull | GlowState::Idle => {}
        }
    }

    fn recede(self: Handle<Self>, app: &mut App, duration: Duration) {
        let state = app.get(self).state;
        if state == GlowState::Recede || state == GlowState::Idle {
            return;
        }
        self.cancel_pull_recede_timer(app);
        app.get_mut(self).pull_recede_timer = None;
        let glow_opacity = self.glow_opacity(app).value(app);
        let glow_opacity_tween = app.get(self).glow_opacity_tween.handle();
        glow_opacity_tween.set_begin(app, Some(glow_opacity));
        glow_opacity_tween.set_end(app, Some(0.0));
        let glow_size = self.glow_size(app).value(app);
        let glow_size_tween = app.get(self).glow_size_tween.handle();
        glow_size_tween.set_begin(app, Some(glow_size));
        glow_size_tween.set_end(app, Some(0.0));
        let glow_controller = app.get(self).glow_controller.handle();
        app.get_mut(glow_controller).duration = Some(duration);
        glow_controller.forward(app, Some(0.0));
        app.get_mut(self).state = GlowState::Recede;
    }

    fn tick_displacement(self: Handle<Self>, app: &mut App, elapsed: Duration) {
        if let Some(last_elapsed) = app.get(self).displacement_ticker_last_elapsed {
            let t = (elapsed.as_micros() as i64 - last_elapsed.as_micros() as i64) as f64;
            let controller = app.get_mut(self);
            controller.displacement = controller.displacement_target
                - (controller.displacement_target - controller.displacement)
                    * 2.0_f64.powf(-t / Self::cross_axis_half_time().as_micros() as f64);
            self.notify_listeners(app);
        }
        let controller = app.get(self);
        if near_equal(
            Some(controller.displacement_target),
            Some(controller.displacement),
            Tolerance::DEFAULT_TOLERANCE.distance,
        ) {
            self.displacement_ticker(app).stop(app, false);
            app.get_mut(self).displacement_ticker_last_elapsed = None;
        } else {
            app.get_mut(self).displacement_ticker_last_elapsed = Some(elapsed);
        }
    }

    fn paint(self: Handle<Self>, app: &App, canvas: &mut Canvas, size: Size) {
        let glow_opacity = self.glow_opacity(app).value(app);
        if glow_opacity == 0.0 {
            return;
        }
        let controller = app.get(self);
        let base_glow_scale = if size.width() > size.height() {
            size.height() / size.width()
        } else {
            1.0
        };
        let radius = size.width() * 3.0 / 2.0;
        let height = f64::min(size.height(), size.width() * Self::WIDTH_TO_HEIGHT_FACTOR);
        let scale_y = self.glow_size(app).value(app) * base_glow_scale;
        let rect = Rect::from_ltwh(0.0, 0.0, size.width(), height);
        let center = Offset::new(
            (size.width() / 2.0) * (0.5 + controller.displacement),
            height - radius,
        );
        #[allow(deprecated)]
        let paint = Paint::from_color(controller.color.with_opacity(glow_opacity).into());
        canvas.save();
        canvas.translate(
            0.0,
            (controller.paint_offset + controller.paint_offset_scroll_pixels) as f32,
        );
        canvas.scale(1.0, scale_y as f32);
        canvas.clip_rect(rect, ClipOp::Intersect, true);
        canvas.draw_circle(center, radius as f32, &paint);
        canvas.restore();
    }
}

impl ChangeNotifier for GlowController {
    fn change_notifier_data(&self) -> &ChangeNotifierData {
        &self.change_notifier
    }

    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
        &mut self.change_notifier
    }
}

impl Debug for GlowController {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "_GlowController(color: {:?}, axis: {:?})",
            self.color, self.axis
        )
    }
}

/// Dart's `_GlowingOverscrollIndicatorPainter`.
struct GlowingOverscrollIndicatorPainter {
    /// The controller for the overscroll glow on the side with negative scroll offsets.
    ///
    /// For a vertical downwards viewport, this is the top side.
    leading_controller: Option<Ref<GlowController>>,

    /// The controller for the overscroll glow on the side with positive scroll offsets.
    ///
    /// For a vertical downwards viewport, this is the bottom side.
    trailing_controller: Option<Ref<GlowController>>,

    /// The direction of the viewport.
    axis_direction: AxisDirection,

    /// Dart's `super.repaint`.
    repaint: Option<Rc<dyn Listenable>>,
}

impl GlowingOverscrollIndicatorPainter {
    const PI_OVER_2: f64 = std::f64::consts::PI / 2.0;

    fn paint_side(
        &self,
        app: &App,
        canvas: &mut Canvas,
        size: Size,
        controller: Option<Handle<GlowController>>,
        axis_direction: AxisDirection,
        growth_direction: GrowthDirection,
    ) {
        let Some(controller) = controller else {
            return;
        };
        match apply_growth_direction_to_axis_direction(axis_direction, growth_direction) {
            AxisDirection::Up => controller.paint(app, canvas, size),
            AxisDirection::Down => {
                canvas.save();
                canvas.translate(0.0, size.height() as f32);
                canvas.scale(1.0, -1.0);
                controller.paint(app, canvas, size);
                canvas.restore();
            }
            AxisDirection::Left => {
                canvas.save();
                canvas.rotate(Self::PI_OVER_2 as f32);
                canvas.scale(1.0, -1.0);
                controller.paint(app, canvas, Size::new(size.height(), size.width()));
                canvas.restore();
            }
            AxisDirection::Right => {
                canvas.save();
                canvas.translate(size.width() as f32, 0.0);
                canvas.rotate(Self::PI_OVER_2 as f32);
                controller.paint(app, canvas, Size::new(size.height(), size.width()));
                canvas.restore();
            }
        }
    }
}

impl CustomPainter for GlowingOverscrollIndicatorPainter {
    fn repaint(&self) -> Option<&Rc<dyn Listenable>> {
        self.repaint.as_ref()
    }

    fn paint(&self, app: &mut App, canvas: &mut Canvas, size: Size) {
        self.paint_side(
            app,
            canvas,
            size,
            self.leading_controller.handle(),
            self.axis_direction,
            GrowthDirection::Reverse,
        );
        self.paint_side(
            app,
            canvas,
            size,
            self.trailing_controller.handle(),
            self.axis_direction,
            GrowthDirection::Forward,
        );
    }

    fn should_repaint(&self, _app: &App, old_delegate: &dyn CustomPainter) -> bool {
        let old_delegate = old_delegate
            .as_any()
            .downcast_ref::<GlowingOverscrollIndicatorPainter>()
            .expect("Dart's covariant parameter");
        old_delegate.leading_controller != self.leading_controller
            || old_delegate.trailing_controller != self.trailing_controller
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl Debug for GlowingOverscrollIndicatorPainter {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "_GlowingOverscrollIndicatorPainter({:?}, {:?})",
            self.leading_controller, self.trailing_controller
        )
    }
}

/// A Material Design visual indication that a scroll view has overscrolled.
///
/// A [`StretchingOverscrollIndicator`] listens for [`ScrollNotification`]s in order
/// to stretch the content of the `Scrollable`. These notifications are typically
/// generated by a `ScrollView`, such as a `ListView` or a `GridView`.
///
/// When triggered, the [`StretchingOverscrollIndicator`] generates an
/// [`OverscrollIndicatorNotification`] before showing an overscroll indication.
/// To prevent the indicator from showing the indication, call
/// [`OverscrollIndicatorNotification::disallow_indicator`] on the notification.
///
/// Created by `MaterialScrollBehavior::build_overscroll_indicator` on platforms
/// (e.g., Android) that commonly use this type of overscroll indication when
/// `ThemeData::use_material3` is true. Otherwise, when `ThemeData::use_material3`
/// is false, a [`GlowingOverscrollIndicator`] is used instead.
///
/// See also:
///
///  * [`OverscrollIndicatorNotification`], which can be used to prevent the
///    stretch effect from being applied at all.
///  * [`NotificationListener`], to listen for the
///    [`OverscrollIndicatorNotification`].
///  * [`GlowingOverscrollIndicator`], the default overscroll indicator for
///    `TargetPlatform::Android` and `TargetPlatform::Fuchsia`.
pub struct StretchingOverscrollIndicator {
    pub key: Option<KeyRef>,

    /// The direction of positive scroll offsets in the `Scrollable` whose
    /// overscrolls are to be visualized.
    pub axis_direction: AxisDirection,

    /// A check that specifies whether a [`ScrollNotification`] should be
    /// handled by this widget.
    ///
    /// By default, checks whether `notification.depth() == 0`. Set it to something
    /// else for more complicated layouts, such as nested `ScrollView`s.
    pub notification_predicate: ScrollNotificationPredicate,

    /// The content will be clipped (or not) according to this option.
    ///
    /// Defaults to [`Clip::HardEdge`].
    pub clip_behavior: Clip,

    /// The widget below this widget in the tree.
    ///
    /// The overscroll indicator will apply a stretch effect to this child. This
    /// child (and its subtree) should include a source of [`ScrollNotification`]
    /// notifications.
    pub child: Option<WidgetRef>,
}

impl StretchingOverscrollIndicator {
    /// Creates a visual indication that a scroll view has overscrolled by
    /// applying a stretch transformation to the content.
    ///
    /// In order for this widget to display an overscroll indication, the [`child`](Self::child)
    /// widget must contain a widget that generates a [`ScrollNotification`], such
    /// as a `ListView` or a `GridView`.
    pub fn new(axis_direction: AxisDirection) -> StretchingOverscrollIndicator {
        StretchingOverscrollIndicator {
            key: None,
            axis_direction,
            notification_predicate: Rc::new(default_scroll_notification_predicate),
            clip_behavior: Clip::HardEdge,
            child: None,
        }
    }

    /// Dart `StretchingOverscrollIndicator(key:)`.
    pub fn key(mut self, key: KeyRef) -> StretchingOverscrollIndicator {
        self.key = Some(key);
        self
    }

    /// Dart `StretchingOverscrollIndicator(notificationPredicate:)`.
    pub fn notification_predicate(
        mut self,
        notification_predicate: ScrollNotificationPredicate,
    ) -> StretchingOverscrollIndicator {
        self.notification_predicate = notification_predicate;
        self
    }

    /// Dart `StretchingOverscrollIndicator(clipBehavior:)`.
    pub fn clip_behavior(mut self, clip_behavior: Clip) -> StretchingOverscrollIndicator {
        self.clip_behavior = clip_behavior;
        self
    }

    /// Dart `StretchingOverscrollIndicator(child:)`.
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> StretchingOverscrollIndicator {
        self.child = Some(child.into_widget());
        self
    }

    /// The axis along which scrolling occurs in the `Scrollable` whose
    /// overscrolls are to be visualized.
    pub fn axis(&self) -> Axis {
        axis_direction_to_axis(self.axis_direction)
    }
}

impl Debug for StretchingOverscrollIndicator {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StretchingOverscrollIndicator")
            .field("axisDirection", &self.axis_direction)
            .finish_non_exhaustive()
    }
}

impl StatefulWidget for StretchingOverscrollIndicator {
    type State = StretchingOverscrollIndicatorState;

    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
        properties.add(EnumProperty::new("axisDirection", self.axis_direction));
    }

    fn create_state(&self) -> StretchingOverscrollIndicatorState {
        StretchingOverscrollIndicatorState {
            state: StateData::new(),
            ticker_provider: TickerProviderStateMixinData::new(),
            stretch_controller: None,
            last_overscroll_notification_metrics: None,
            total_overscroll: 0.0,
            accepted: true,
        }
    }
}

/// Dart's `_StretchingOverscrollIndicatorState`.
pub struct StretchingOverscrollIndicatorState {
    state: StateData<StretchingOverscrollIndicator>,
    ticker_provider: TickerProviderStateMixinData,
    /// Dart's `late final _stretchController`, made on first use, with the `Listenable` the
    /// builder listens to, made once so a rebuild hands the builder the same one.
    stretch_controller: Option<(Ref<StretchController>, Rc<dyn Listenable>)>,
    /// The metrics of Dart's `_lastOverscrollNotification`, the one member of it `build`
    /// reads.
    last_overscroll_notification_metrics:
        Option<Rc<dyn crate::widgets::scroll_metrics::ScrollMetrics>>,
    total_overscroll: f64,
    accepted: bool,
}

impl StretchingOverscrollIndicatorState {
    fn stretch_controller(self: Handle<Self>, app: &mut App) -> Handle<StretchController> {
        self.stretch_listenable_controller(app).0
    }

    fn stretch_listenable_controller(
        self: Handle<Self>,
        app: &mut App,
    ) -> (Handle<StretchController>, Rc<dyn Listenable>) {
        if let Some((controller, listenable)) = &app.get(self).stretch_controller {
            return (controller.handle(), Rc::clone(listenable));
        }
        let controller = StretchController::new(app, TickerProviderRef::new(self));
        let handle = controller.handle();
        let listenable: Rc<dyn Listenable> = Rc::new(controller.clone());
        app.get_mut(self).stretch_controller = Some((controller, Rc::clone(&listenable)));
        (handle, listenable)
    }

    fn handle_scroll_notification(
        self: Handle<Self>,
        app: &mut App,
        notification: &dyn ScrollNotification,
    ) -> bool {
        let widget = self.widget(app);
        let notification_predicate = Rc::clone(&widget.notification_predicate);
        let axis = widget.axis();
        if !notification_predicate(notification) {
            return false;
        }
        if notification.metrics().axis() != axis {
            // This widget is explicitly configured to one axis. If a notification
            // from a different axis bubbles up, do nothing.
            return false;
        }
        let any = notification.as_any();
        if any.is::<ScrollStartNotification>() {
            let state = app.get_mut(self);
            state.accepted = true;
            state.total_overscroll = 0.0;
        } else if let Some(notification) = any.downcast_ref::<OverscrollNotification>() {
            app.get_mut(self).last_overscroll_notification_metrics =
                Some(Rc::clone(notification.metrics()));
            // Dart's `_lastNotification.runtimeType is! OverscrollNotification` (see the
            // module doc).
            let confirmation_notification =
                OverscrollIndicatorNotification::new(notification.overscroll < 0.0);
            confirmation_notification.dispatch(app, Some(self.context(app)));
            app.get_mut(self).accepted = confirmation_notification.accepted.get();

            if app.get(self).accepted {
                app.get_mut(self).total_overscroll += notification.overscroll;

                if notification.velocity != 0.0 {
                    debug_assert!(notification.drag_details.is_none());
                    self.stretch_controller(app)
                        .absorb_impact(app, notification.velocity);
                } else {
                    debug_assert!(notification.overscroll != 0.0);
                    if notification.drag_details.is_some() {
                        // We clamp the overscroll amount relative to the length of the viewport,
                        // which is the furthest distance a single pointer could pull on the
                        // screen. This is because more than one pointer will multiply the
                        // amount of overscroll - https://github.com/flutter/flutter/issues/11884

                        let viewport_dimension = notification.metrics().viewport_dimension();
                        let distance_for_pull = app.get(self).total_overscroll / viewport_dimension;
                        let clamped_overscroll = clamp_double(distance_for_pull, -1.0, 1.0);
                        self.stretch_controller(app).pull(app, clamped_overscroll);
                    }
                }
            }
        } else if let Some(notification) = any.downcast_ref::<ScrollEndNotification>() {
            let mut velocity = match axis {
                Axis::Vertical => notification
                    .drag_details
                    .as_ref()
                    .map_or(0.0, |details| details.velocity.pixels_per_second.dy()),
                Axis::Horizontal => notification
                    .drag_details
                    .as_ref()
                    .map_or(0.0, |details| details.velocity.pixels_per_second.dx()),
            };

            // Reverse axis directions report dragDetails velocity in
            // the opposite screen coordinate, so the value must be inverted.
            if matches!(
                notification.metrics().axis_direction(),
                AxisDirection::Left | AxisDirection::Up
            ) {
                velocity = -velocity;
            }

            // Since the overscrolling ended, we reset the total overscroll amount.
            app.get_mut(self).total_overscroll = 0.0;
            if app.get(self).accepted {
                self.stretch_controller(app).scroll_end(app, velocity);
            }
        } else if any.is::<ScrollUpdateNotification>() {
            app.get_mut(self).total_overscroll = 0.0;
            self.stretch_controller(app).scroll_end(app, 0.0);
        }
        false
    }

    /// The body of the `AnimatedBuilder` Dart's `build` returns.
    fn build_stretch(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
        let stretch = self.stretch_controller(app).overscroll(app);
        let widget = self.widget(app);
        let (axis, axis_direction, clip_behavior) =
            (widget.axis(), widget.axis_direction, widget.clip_behavior);
        let child = widget
            .child
            .clone()
            .unwrap_or_else(|| SizedBox::shrink().into_widget());

        let main_axis_size = match axis {
            Axis::Horizontal => MediaQuery::width_of(app, context),
            Axis::Vertical => MediaQuery::height_of(app, context),
        };

        let viewport_dimension = app
            .get(self)
            .last_overscroll_notification_metrics
            .as_ref()
            .map_or(main_axis_size, |metrics| metrics.viewport_dimension());

        let mut overscroll = -stretch;

        // Adjust overscroll for reverse scroll directions.
        if axis_direction == AxisDirection::Up || axis_direction == AxisDirection::Left {
            overscroll = -overscroll;
        }

        let transform = StretchEffect::new(axis, child).stretch_strength(overscroll);

        // Only clip if the viewport dimension is smaller than that of the
        // screen size in the main axis. If the viewport takes up the whole
        // screen, overflow from transforming the viewport is irrelevant.
        ClipRect::new()
            .clip_behavior(if stretch != 0.0 && viewport_dimension != main_axis_size {
                clip_behavior
            } else {
                Clip::None
            })
            .child(transform)
            .into_widget()
    }
}

impl Debug for StretchingOverscrollIndicatorState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StretchingOverscrollIndicatorState")
            .finish_non_exhaustive()
    }
}

impl TickerProviderStateMixin for StretchingOverscrollIndicatorState {
    fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
        &app.get(self).ticker_provider
    }

    fn ticker_provider_data_mut(
        self: Handle<Self>,
        app: &mut App,
    ) -> &mut TickerProviderStateMixinData {
        &mut app.get_mut(self).ticker_provider
    }
}

impl TickerProviderObject for StretchingOverscrollIndicatorState {
    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
        TickerProviderStateMixin::create_ticker(self, app, on_tick)
    }
}

impl State for StretchingOverscrollIndicatorState {
    type Widget = StretchingOverscrollIndicator;
    crate::state_accessors!();

    fn activate(self: Handle<Self>, app: &mut App) {
        TickerProviderStateMixin::activate(self, app);
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        self.stretch_controller(app).dispose(app);
        TickerProviderStateMixin::dispose(self, app);
    }

    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
        let (_, stretch_listenable) = self.stretch_listenable_controller(app);
        NotificationListener::<dyn ScrollNotification>::new(
            AnimatedBuilder::new(
                stretch_listenable,
                move |app: &mut App, context: BuildContext, _child: Option<&WidgetRef>| {
                    self.build_stretch(app, context)
                },
            )
            .into_widget(),
        )
        .on_notification(
            move |app: &mut App, notification: &dyn ScrollNotification| {
                self.handle_scroll_notification(app, notification)
            },
        )
        .into_widget()
    }
}

/// Dart's `_StretchController`, a `Listenable` that forwards its listeners to the notifier
/// of its [`overscroll`](Self::overscroll).
struct StretchController {
    vsync: TickerProviderRef,
    controller: Option<Ref<AnimationController>>,

    /// Manages and notifies changes to the current [`overscroll`](Self::overscroll) value.
    overscroll_notifier: Ref<ValueNotifier<f64>>,

    /// Stores the `overscroll` value from an ongoing animation at the precise
    /// moment it is interrupted by a new `pull()` gesture.
    ///
    /// When `pull()` is called while an animation (triggered by `absorb_impact`
    /// or `scroll_end`) is active, this field captures the animation's current
    /// `controller.value` (which represents the overscroll amount) immediately
    /// before the animation controller is disposed.
    ///
    /// This captured value is then added to the overscroll amount calculated
    /// by the `pull()` method. The primary purpose is to create a smoother
    /// visual transition from an animated overscroll state to a direct,
    /// user-driven pull, minimizing any abrupt visual "jumps" in the
    /// stretch effect.
    ///
    /// It is reset to `0.0` when an animation completes naturally via `animate()`
    /// or when a new pull starts without a preceding active animation.
    interrupted_overscroll: f64,
}

impl StretchController {
    // Constants from Android.
    const EXPONENTIAL_SCALAR: f64 = std::f64::consts::E / 0.33;
    const STRETCH_INTENSITY: f64 = 0.016;

    const MIN_OVERSCROLL: f64 = -1.0;
    const MAX_OVERSCROLL: f64 = 1.0;

    /// A fraction used to adjust the input velocity, measured in pixels,
    /// to a value between -1 and 1 when gesture fling.
    const FLING_VELOCITY_FRICTION: f64 = 1.0 / 6000.0;

    /// A fraction used to scale the absorbed impact velocity,
    /// converting raw velocity into a normalized value for simulation.
    const ABSORB_IMPACT_VELOCITY_FRICTION: f64 = 1.0 / 3000.0;

    /// The maximum velocity allowed for a fling after scaling
    /// to prevent applying an excessive stretch effect.
    const MAX_FLING_VELOCITY: f64 = 0.5;

    /// The maximum velocity allowed when absorbing an impact,
    /// ensuring the stretch effect does not exceed a reasonable limit.
    const MAX_ABSORB_IMPACT_VELOCITY: f64 = 1.25;

    // Physical constants ported directly from Android's EdgeEffect.java.
    //
    // Android's EdgeEffect.java:
    // https://cs.android.com/android/platform/superproject/main/+/main:frameworks/base/core/java/android/widget/EdgeEffect.java
    const K_NATURAL_FREQUENCY: f64 = 24.657;
    const K_DAMPING_RATIO: f64 = 0.98;

    /// A correction factor applied to the simulation time.
    ///
    /// The physical constants `K_NATURAL_FREQUENCY` and `K_DAMPING_RATIO` were ported
    /// directly from Android's `EdgeEffect.java` source. However, using these
    /// constants as-is resulted in an animation that was noticeably faster than
    /// the native Android behavior. The underlying reason for this discrepancy is
    /// unknown.
    ///
    /// This factor, determined by visual comparison ("eyeballing") to match the
    /// platform's timing, is applied to the elapsed time `t` to slow down the
    /// simulation.
    ///
    /// Based on the damped harmonic oscillator equations, an alternative,
    /// mathematically equivalent, approach would be to multiply both the
    /// `K_NATURAL_FREQUENCY` and the initial velocity by this same factor,
    /// rather than scaling the time input.
    const K_TIME_CORRECTION_FACTOR: f64 = 0.8;

    /// Stiffness coefficient for the spring, derived from the natural frequency.
    ///
    /// Calculated as `K_STIFFNESS = K_NATURAL_FREQUENCY^2`, this is the baseline
    /// spring constant used in the damped harmonic oscillator model.
    const K_STIFFNESS: f64 = Self::K_NATURAL_FREQUENCY * Self::K_NATURAL_FREQUENCY;

    /// Spring description representing the stretch behavior of the edge effect.
    ///
    /// This [`SpringDescription`] is used to simulate the overscroll stretch.
    /// The spring has a mass of 1, a stiffness adjusted by the
    /// [`K_TIME_CORRECTION_FACTOR`](Self::K_TIME_CORRECTION_FACTOR) squared to match
    /// platform timing, and a damping ratio corresponding to Android's native `EdgeEffect`.
    fn stretch_spring_description() -> SpringDescription {
        SpringDescription::with_damping_ratio_value(
            1.0,
            Self::K_STIFFNESS * Self::K_TIME_CORRECTION_FACTOR * Self::K_TIME_CORRECTION_FACTOR,
            Self::K_DAMPING_RATIO,
        )
    }

    fn new(app: &mut App, vsync: TickerProviderRef) -> Ref<StretchController> {
        let overscroll_notifier = app.create(ValueNotifier::new(0.0));
        app.create(StretchController {
            vsync,
            controller: None,
            overscroll_notifier,
            interrupted_overscroll: 0.0,
        })
    }

    fn overscroll(self: Handle<Self>, app: &App) -> f64 {
        *app.get(&app.get(self).overscroll_notifier).value()
    }

    fn set_overscroll(self: Handle<Self>, app: &mut App, new_value: f64) {
        let notifier = app.get(self).overscroll_notifier.handle();
        notifier.set_value(
            app,
            clamp_double(new_value, Self::MIN_OVERSCROLL, Self::MAX_OVERSCROLL),
        );
    }

    /// Creates a stretching-only [`Simulation`] ported from Android 12.
    fn create_stretch_simulation(self: Handle<Self>, app: &App, velocity: f64) -> SpringSimulation {
        SpringSimulation::new(
            Self::stretch_spring_description(),
            self.overscroll(app),
            0.0,
            velocity * Self::K_TIME_CORRECTION_FACTOR,
        )
    }

    /// Handle a fling to the edge of the viewport at a particular velocity.
    ///
    /// The velocity must be positive.
    fn absorb_impact(self: Handle<Self>, app: &mut App, velocity: f64) {
        if velocity == 0.0 {
            return;
        }
        let scaled_velocity = clamp_double(
            velocity * Self::ABSORB_IMPACT_VELOCITY_FRICTION,
            -Self::MAX_ABSORB_IMPACT_VELOCITY,
            Self::MAX_ABSORB_IMPACT_VELOCITY,
        );

        let simulation = self.create_stretch_simulation(app, scaled_velocity);
        self.animate(app, Box::new(simulation));
    }

    /// Called when the overscroll ends to trigger a fling animation if needed.
    fn scroll_end(self: Handle<Self>, app: &mut App, velocity: f64) {
        if velocity == 0.0 && self.overscroll(app) == 0.0 {
            return;
        }
        let scaled_velocity = clamp_double(
            -(velocity * Self::FLING_VELOCITY_FRICTION),
            -Self::MAX_FLING_VELOCITY,
            Self::MAX_FLING_VELOCITY,
        );

        if app.get(self).controller.is_none() {
            let simulation = self.create_stretch_simulation(app, scaled_velocity);
            self.animate(app, Box::new(simulation));
        }
    }

    /// Starts a new animation using the given `simulation`.
    ///
    /// Disposes any existing animation controller before starting a new one.
    /// Updates the [`overscroll`](Self::overscroll) value on each animation frame.
    /// Automatically disposes the controller when the animation completes.
    fn animate(self: Handle<Self>, app: &mut App, simulation: Box<dyn Simulation>) {
        let vsync = app.get(self).vsync.clone();
        let controller = AnimationController::unbounded(
            app,
            0.0,
            None,
            None,
            AnimationBehavior::Preserve,
            vsync,
        );
        controller.view().add_listener(
            app,
            Listener::new(move |app: &mut App| {
                let new_overscroll = app
                    .get(self)
                    .controller
                    .handle()
                    .map_or(0.0, |controller| controller.value(app));
                self.set_overscroll(app, new_overscroll);
            }),
        );
        // The completion is the controller's own: it names the controller without keeping it.
        let handle = controller.handle();
        controller.animate_with(app, simulation).when_complete(
            app,
            Listener::new(move |app: &mut App| {
                let controller = handle;
                // Only clean up if this controller is still the active one. A later
                // pull(), animate(), or dispose() may have already replaced and disposed
                // it, in which case that path owns the cleanup and this stale completion
                // callback must not touch the shared state (or double dispose the
                // controller).
                if app.get(self).controller.handle() == Some(controller) {
                    self.set_overscroll(app, 0.0);
                    app.get_mut(self).interrupted_overscroll = 0.0;
                    controller.dispose(app);
                    app.get_mut(self).controller = None;
                }
            }),
        );

        if let Some(old_controller) = app.get(self).controller.handle() {
            old_controller.dispose(app);
        }
        app.get_mut(self).controller = Some(controller);
    }

    /// Handle a user-driven overscroll.
    ///
    /// The `normalized_overscroll` argument should be the scroll distance in
    /// logical pixels, divided by the extent of the viewport in the main axis.
    fn pull(self: Handle<Self>, app: &mut App, normalized_overscroll: f64) {
        if let Some(controller) = app.get(self).controller.handle() {
            app.get_mut(self).interrupted_overscroll = controller.value(app);
            controller.dispose(app);
            app.get_mut(self).controller = None;
        }

        let pull_distance = normalized_overscroll;
        let abs_distance = pull_distance.abs();
        let linear_intensity = Self::STRETCH_INTENSITY * abs_distance;
        let exponential_intensity =
            Self::STRETCH_INTENSITY * (1.0 - (-abs_distance * Self::EXPONENTIAL_SCALAR).exp());

        // Maintain sign of overscroll for direction; Dart's `double.sign` is zero for zero,
        // where `f64::signum` is one.
        let direction_sign = if pull_distance > 0.0 {
            1.0
        } else if pull_distance < 0.0 {
            -1.0
        } else {
            pull_distance
        };
        let new_overscroll = direction_sign * (linear_intensity + exponential_intensity);
        let interrupted_overscroll = app.get(self).interrupted_overscroll;
        self.set_overscroll(app, new_overscroll + interrupted_overscroll);
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        if let Some(controller) = app.get_mut(self).controller.take() {
            controller.dispose(app);
        }
        let notifier = app.get(self).overscroll_notifier.handle();
        notifier.dispose(app);
    }
}

impl ListenableObject for StretchController {
    fn add_listener(self: Handle<Self>, app: &mut App, listener: Listener) {
        let notifier = app.get(self).overscroll_notifier.handle();
        notifier.add_listener(app, listener);
    }

    fn remove_listener(self: Handle<Self>, app: &mut App, listener: &Listener) {
        let notifier = app.get(self).overscroll_notifier.handle();
        notifier.remove_listener(app, listener);
    }
}

impl Debug for StretchController {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("_StretchController()")
    }
}

/// A notification that either a [`GlowingOverscrollIndicator`] or a
/// [`StretchingOverscrollIndicator`] will start showing an overscroll indication.
///
/// To prevent the indicator from showing the indication, call
/// [`disallow_indicator`](Self::disallow_indicator) on the notification.
///
/// A listener writes [`paint_offset`](Self::paint_offset) and
/// [`accepted`](Self::accepted) through a shared reference, as the notification bubbles as
/// `&dyn Notification`; the indicator reads them back once the dispatch returns.
///
/// See also:
///
///  * [`GlowingOverscrollIndicator`], which generates this type of notification
///    by painting an indicator over the child content.
///  * [`StretchingOverscrollIndicator`], which generates this type of
///    notification by applying a stretch transformation to the child content.
pub struct OverscrollIndicatorNotification {
    viewport_notification: ViewportNotificationData,

    /// Whether the indication will be shown on the leading edge of the scroll
    /// view.
    pub leading: bool,

    /// Controls at which offset a [`GlowingOverscrollIndicator`] draws.
    ///
    /// A positive offset will move the glow away from its edge,
    /// i.e. for a vertical, [`leading`](Self::leading) indicator, a
    /// [`paint_offset`](Self::paint_offset) of 100.0 will draw the indicator 100.0 pixels
    /// from the top of the edge. For a vertical indicator with [`leading`](Self::leading)
    /// set to `false`, a [`paint_offset`](Self::paint_offset) of 100.0 will draw the indicator
    /// 100.0 pixels from the bottom instead.
    ///
    /// A negative [`paint_offset`](Self::paint_offset) is generally not useful, since the
    /// glow will be clipped.
    ///
    /// This has no effect on a [`StretchingOverscrollIndicator`].
    pub paint_offset: Cell<f64>,

    /// Whether the current overscroll event will allow for the indicator to be
    /// shown.
    ///
    /// Calling [`disallow_indicator`](Self::disallow_indicator) sets this to false,
    /// preventing the over scroll indicator from showing.
    ///
    /// Defaults to true.
    pub accepted: Cell<bool>,
}

impl OverscrollIndicatorNotification {
    /// Creates a notification that an [`GlowingOverscrollIndicator`] or a
    /// [`StretchingOverscrollIndicator`] will start showing an overscroll indication.
    pub fn new(leading: bool) -> OverscrollIndicatorNotification {
        OverscrollIndicatorNotification {
            viewport_notification: ViewportNotificationData::new(),
            leading,
            paint_offset: Cell::new(0.0),
            accepted: Cell::new(true),
        }
    }

    /// Call this method if the overscroll indicator should be prevented.
    pub fn disallow_indicator(&self) {
        self.accepted.set(false);
    }
}

impl Notification for OverscrollIndicatorNotification {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn viewport_depth(&self) -> Option<&Cell<u32>> {
        Some(self.viewport_notification.depth_cell())
    }
}

impl ViewportNotificationMixin for OverscrollIndicatorNotification {
    fn viewport_notification_data(&self) -> &ViewportNotificationData {
        &self.viewport_notification
    }
}

impl Debug for OverscrollIndicatorNotification {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut description = Vec::new();
        ViewportNotificationMixin::debug_fill_description(self, &mut description);
        description.push(format!(
            "side: {}",
            if self.leading {
                "leading edge"
            } else {
                "trailing edge"
            }
        ));
        write!(
            f,
            "OverscrollIndicatorNotification({})",
            description.join(", ")
        )
    }
}

#[cfg(test)]
mod tests {
    use waft_foundation::OptionRetained;

    use waft_embedder::TextDirection;
    use waft_embedder::valo::Op;
    use waft_foundation::UniqueKey;
    use waft_gestures::{DragEndDetails, DragStartDetails, DragUpdateDetails, Velocity};
    use waft_painting::EdgeInsetsGeometry;
    use waft_physics::Simulation;
    use waft_rendering::{
        RenderBox, RenderClipRect, RenderCustomClip, RenderCustomPaint, RenderHandle,
    };

    use super::*;
    use crate::binding::WidgetsBinding;
    use crate::framework::GlobalKey;
    use crate::testing::{TestPointer, WidgetTester, test_widgets};
    use crate::testing::{assert_f32_equals, expect, find, finds_nothing, finds_one_widget};
    use crate::widgets::basic::{
        Center, Column, Directionality, Opacity, Padding, SliverToBoxAdapter,
    };
    use crate::widgets::container::Container;
    use crate::widgets::media_query::MediaQueryData;
    use crate::widgets::page_view::PageView;
    use crate::widgets::scroll_configuration::{
        ScrollBehavior, ScrollBehaviorRef, ScrollConfiguration,
    };
    use crate::widgets::scroll_controller::{ScrollController, ScrollControllerLeaf};
    use crate::widgets::scroll_metrics::ScrollMetrics;
    use crate::widgets::scroll_physics::{
        AlwaysScrollableScrollPhysics, ScrollPhysics, ScrollPhysicsBase, ScrollPhysicsRef,
    };
    use crate::widgets::scroll_simulation::ClampingScrollSimulation;
    use crate::widgets::scroll_view::{CustomScrollView, ListView};
    use crate::widgets::scrollable_helpers::ScrollableDetails;
    use crate::widgets::single_child_scroll_view::SingleChildScrollView;
    use crate::widgets::sliver::SliverList;
    use crate::widgets::text::Text;
    use waft_rendering::testing::{PaintCall, RecordedCall, assert_paints, paints};

    // ---- what these tests read from a `WidgetTester` ----

    /// `tester.getCenter(find.byType(CustomScrollView))` for a scroll view that fills the view.
    const VIEW_CENTER: Offset = Offset::new(
        WidgetTester::SIZE.width() / 2.0,
        WidgetTester::SIZE.height() / 2.0,
    );

    /// The glow tests' `slowDrag`: ten moves by `offset`, 20ms apart, of the touch `pointer`.
    fn slow_drag(tester: &mut WidgetTester, start: Offset, offset: Offset, pointer: i64) {
        let mut gesture = TestPointer::touch(pointer);
        tester.down(&mut gesture, start);
        for _ in 0..10 {
            tester.move_by(&mut gesture, offset, true);
            tester.pump_by(Duration::from_millis(20));
        }
        tester.up(&gesture);
    }

    /// `tester.layers.contains(isA<ImageFilterLayer>())`.
    fn has_image_filter_layer(tester: &WidgetTester) -> bool {
        let root = tester
            .update(|app| WidgetsBinding::instance(app).root_element(app))
            .expect("a mounted tree");
        let layers = tester.layer_list_of(root);
        let app = tester.cell.borrow();
        layers.into_iter().any(|layer| {
            app.handle::<waft_rendering::ImageFilterLayer>(layer.id())
                .is_some()
        })
    }

    /// The mounted `StretchEffect`'s strength: `findStretchEffect(tester).stretchStrength`.
    fn stretch_strength(tester: &WidgetTester) -> f64 {
        tester.widget(
            find::by_type::<StretchEffect>(),
            |effect: &StretchEffect| effect.stretch_strength,
        )
    }

    /// `tester.renderObject(find.byType(CustomPaint))`, first to last.
    fn custom_paints(tester: &WidgetTester) -> Vec<RenderHandle<RenderCustomPaint>> {
        tester.all::<RenderCustomPaint>()
    }

    /// The one `RenderCustomPaint`: `tester.renderObject(find.byType(CustomPaint))`.
    fn custom_paint(tester: &WidgetTester) -> RenderHandle<RenderCustomPaint> {
        let paints = custom_paints(tester);
        assert_eq!(paints.len(), 1, "one CustomPaint");
        paints[0]
    }

    /// The global rect the first `RenderClipRect` clips its child to: its own box, as the
    /// stretch's `ClipRect` has no clipper.
    fn first_clip_rect(tester: &WidgetTester) -> Rect {
        let clip = tester.first::<RenderClipRect>();
        tester.get_rect(clip.as_box())
    }

    /// `tester.allRenderObjects.whereType<RenderClipRect>().first.clipBehavior`.
    fn first_clip_behavior(tester: &WidgetTester) -> Clip {
        let clip = tester.first::<RenderClipRect>();
        clip.clip_behavior(&tester.cell.borrow())
    }

    /// The calls `custom_paint` makes for its foreground painter when it paints at offset
    /// zero, the recording Flutter's `paints` matcher walks; the child's own calls, which
    /// these patterns skip over, are left out.
    fn painted(tester: &WidgetTester, custom_paint: RenderHandle<RenderCustomPaint>) -> Vec<Op> {
        let mut app = tester.cell.borrow_mut();
        let painter = custom_paint
            .foreground_painter(&app)
            .expect("the indicator paints in the foreground");
        let size = custom_paint.size(&app);
        let mut canvas = Canvas::new();
        canvas.save();
        painter.paint(&mut app, &mut canvas, size);
        canvas.restore();
        canvas.build().ops().to_vec()
    }

    /// `box.localToGlobal(Offset.zero)` for the box under `key`.
    fn origin_of(tester: &WidgetTester, key: &GlobalKey) -> Offset {
        let render_box = tester.render_object(key).as_box().expect("a render box");
        render_box.local_to_global(&tester.cell.borrow(), Offset::ZERO, None)
    }

    /// The glow tests' `doesNotOverscroll`: `isNot(paints..circle())`.
    fn does_not_overscroll(ops: &[Op]) -> bool {
        paints(ops, &[circle()]).is_err()
    }

    fn circle() -> PaintCall {
        PaintCall::circle(None)
    }

    /// `..circle(x:, color:)`.
    fn circle_with(x: Option<f64>, color: Option<u32>) -> PaintCall {
        PaintCall::Circle {
            x,
            y: None,
            radius: None,
            color: color.map(Color::new),
            style: None,
        }
    }

    // ---- the trees the tests build ----

    fn ltr<K>(child: impl IntoWidget<K>) -> WidgetRef {
        Directionality::new(TextDirection::Ltr, child).into_widget()
    }

    /// `CustomScrollView(slivers: [SliverToBoxAdapter(child: SizedBox(height: height))])`.
    fn sized_scroll_view(height: f64) -> CustomScrollView {
        CustomScrollView::new().slivers([SliverToBoxAdapter::new()
            .child(SizedBox::new().height(height))
            .into_widget()])
    }

    fn always_scrollable() -> ScrollPhysicsRef {
        Rc::new(AlwaysScrollableScrollPhysics::new())
    }

    /// `overscroll_indicator_test.dart`'s `TestScrollBehavior1` (`COLOR` green),
    /// `TestScrollBehavior2` (blue) and `TestScrollBehaviorNoGlow` (zero): a glow of `COLOR`,
    /// or none. Each is a type of its own, as Dart's three classes are, so swapping one for
    /// another rebuilds the scrollables under it.
    #[derive(Debug)]
    struct TestScrollBehavior<const COLOR: u32>;

    impl<const COLOR: u32> ScrollBehavior for TestScrollBehavior<COLOR> {
        fn as_any(&self) -> &dyn std::any::Any {
            self
        }

        fn build_overscroll_indicator(
            &self,
            _app: &mut App,
            _context: BuildContext,
            child: WidgetRef,
            details: &ScrollableDetails,
        ) -> WidgetRef {
            if COLOR == 0 {
                return child;
            }
            GlowingOverscrollIndicator::new(details.direction, Color::new(COLOR))
                .child(child)
                .into_widget()
        }
    }

    fn behavior<const COLOR: u32>() -> ScrollBehaviorRef {
        ScrollBehaviorRef::new(TestScrollBehavior::<COLOR>)
    }

    /// A listener that sets `paint_offset` on the confirmations `side` picks.
    fn paint_offset_listener(
        child: WidgetRef,
        side: impl Fn(bool) -> bool + 'static,
        paint_offset: f64,
    ) -> WidgetRef {
        NotificationListener::<OverscrollIndicatorNotification>::new(child)
            .on_notification(move |_app, notification| {
                if side(notification.leading) {
                    notification.paint_offset.set(paint_offset);
                }
                false
            })
            .into_widget()
    }

    // ---- overscroll_indicator_test.dart ----

    /// "Overscroll indicator color".
    #[test]
    fn the_default_glow_is_white_and_shows_only_for_a_slow_drag() {
        test_widgets(|tester| {
            tester.pump_widget(ltr(sized_scroll_view(2000.0)));
            let painter = custom_paint(tester);

            assert!(does_not_overscroll(&painted(tester, painter)));

            // the scroll gesture from tester.scroll happens in zero time, so nothing should appear:
            tester.drag_from(VIEW_CENTER, Offset::new(0.0, 100.0), 1);
            assert!(does_not_overscroll(&painted(tester, painter)));
            tester.pump(); // allow the ticker to register itself
            assert!(does_not_overscroll(&painted(tester, painter)));
            tester.pump_by(Duration::from_millis(100)); // animate
            assert!(does_not_overscroll(&painted(tester, painter)));

            let mut gesture = TestPointer::touch(2);
            tester.down(&mut gesture, Offset::new(200.0, 200.0));
            tester.pump_by(Duration::from_millis(100)); // animate
            assert!(does_not_overscroll(&painted(tester, painter)));
            tester.up(&gesture);
            assert!(does_not_overscroll(&painted(tester, painter)));

            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, 5.0), 3);
            assert_paints(
                &painted(tester, painter),
                &[circle_with(None, Some(0x0DFFFFFF))],
            );

            tester.pump_and_settle_by(Duration::from_secs(1));
            assert!(does_not_overscroll(&painted(tester, painter)));
        });
    }

    /// "Nested scrollable".
    #[test]
    fn a_predicate_lets_the_outer_indicator_glow_for_the_inner_scrollable() {
        test_widgets(|tester| {
            tester.pump_widget(ltr(GlowingOverscrollIndicator::new(
                AxisDirection::Down,
                Color::new(0x0DFFFFFF),
            )
            .notification_predicate(Rc::new(|notification| notification.depth() == 1))
            .child(
                SingleChildScrollView::new()
                    .scroll_direction(Axis::Horizontal)
                    .child(
                        SizedBox::new()
                            .width(600.0)
                            .child(sized_scroll_view(2000.0)),
                    ),
            )));

            let paints_found = custom_paints(tester);
            let outer_painter = paints_found[0];
            let inner_painter = *paints_found.last().expect("two CustomPaints");

            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, 5.0), 1);
            assert_paints(&painted(tester, outer_painter), &[circle()]);
            assert_paints(&painted(tester, inner_painter), &[circle()]);
        });
    }

    /// "Overscroll indicator changes side when you drag on the other side".
    #[test]
    fn the_glow_centers_on_the_side_the_drag_is_on() {
        test_widgets(|tester| {
            tester.pump_widget(ltr(sized_scroll_view(2000.0)));
            let painter = custom_paint(tester);

            slow_drag(tester, Offset::new(400.0, 200.0), Offset::new(0.0, 10.0), 1);
            assert_paints(&painted(tester, painter), &[circle_with(Some(400.0), None)]);
            slow_drag(tester, Offset::new(100.0, 200.0), Offset::new(0.0, 10.0), 2);
            assert_paints(
                &painted(tester, painter),
                &[PaintCall::something(|call| match call {
                    RecordedCall::Circle { center, .. } if center.dx() < 400.0 => Ok(true),
                    RecordedCall::Circle { .. } => Err(
                        "Dragging on left hand side did not overscroll on left hand side.".into(),
                    ),
                    _ => Ok(false),
                })],
            );
            slow_drag(tester, Offset::new(700.0, 200.0), Offset::new(0.0, 10.0), 3);
            assert_paints(
                &painted(tester, painter),
                &[PaintCall::something(|call| match call {
                    RecordedCall::Circle { center, .. } if center.dx() > 400.0 => Ok(true),
                    RecordedCall::Circle { .. } => Err(
                        "Dragging on right hand side did not overscroll on right hand side.".into(),
                    ),
                    _ => Ok(false),
                })],
            );

            tester.pump_and_settle_by(Duration::from_secs(1));
            assert!(does_not_overscroll(&painted(tester, painter)));
        });
    }

    /// "Overscroll indicator changes side when you shift sides".
    #[test]
    fn the_glow_follows_a_drag_that_slides_sideways() {
        test_widgets(|tester| {
            tester.pump_widget(ltr(sized_scroll_view(2000.0)));
            let painter = custom_paint(tester);
            let mut gesture = TestPointer::touch(1);
            tester.down(&mut gesture, Offset::new(300.0, 200.0));
            tester.move_by(&mut gesture, Offset::new(0.0, 10.0), true);
            tester.pump_by(Duration::from_millis(20));
            let old_x = Rc::new(std::cell::Cell::new(0.0));
            for _ in 0..10 {
                tester.move_by(&mut gesture, Offset::new(50.0, 50.0), true);
                tester.pump_by(Duration::from_millis(20));
                assert_paints(
                    &painted(tester, painter),
                    &[PaintCall::something({
                        let old_x = Rc::clone(&old_x);
                        move |call| match call {
                            RecordedCall::Circle { center, .. } => {
                                if center.dx() <= old_x.get() {
                                    return Err("Sliding to the right did not make the center of \
                                                the radius slide to the right."
                                        .into());
                                }
                                old_x.set(center.dx());
                                Ok(true)
                            }
                            _ => Ok(false),
                        }
                    })],
                );
            }
            tester.up(&gesture);

            tester.pump_and_settle_by(Duration::from_secs(1));
            assert!(does_not_overscroll(&painted(tester, painter)));
        });
    }

    /// "Flipping direction of scrollable doesn't change overscroll behavior": "down".
    #[test]
    fn a_downward_scroll_view_glows_at_the_top_when_pulled_down() {
        test_widgets(|tester| {
            tester.pump_widget(ltr(sized_scroll_view(20.0).physics(always_scrollable())));
            let painter = custom_paint(tester);
            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, 5.0), 1);
            assert_paints(
                &painted(tester, painter),
                &[
                    PaintCall::Save,
                    circle(),
                    PaintCall::Restore,
                    PaintCall::Save,
                    PaintCall::scale(None, Some(-1.0)),
                    PaintCall::Restore,
                    PaintCall::Restore,
                ],
            );

            tester.pump_and_settle_by(Duration::from_secs(1));
            assert!(does_not_overscroll(&painted(tester, painter)));
        });
    }

    /// "Flipping direction of scrollable doesn't change overscroll behavior": "up".
    #[test]
    fn a_reversed_scroll_view_glows_at_the_top_when_pulled_down() {
        test_widgets(|tester| {
            tester.pump_widget(ltr(sized_scroll_view(20.0)
                .reverse(true)
                .physics(always_scrollable())));
            let painter = custom_paint(tester);
            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, 5.0), 1);
            assert_paints(
                &painted(tester, painter),
                &[
                    PaintCall::Save,
                    PaintCall::scale(None, Some(-1.0)),
                    PaintCall::Restore,
                    PaintCall::Save,
                    circle(),
                    PaintCall::Restore,
                    PaintCall::Restore,
                ],
            );

            tester.pump_and_settle_by(Duration::from_secs(1));
            assert!(does_not_overscroll(&painted(tester, painter)));
        });
    }

    /// "Overscroll in both directions".
    #[test]
    fn pulling_one_way_then_the_other_glows_at_both_ends() {
        test_widgets(|tester| {
            tester.pump_widget(ltr(sized_scroll_view(20.0).physics(always_scrollable())));
            let painter = custom_paint(tester);
            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, 5.0), 1);
            assert_paints(&painted(tester, painter), &[circle()]);
            assert!(paints(&painted(tester, painter), &[circle(), circle()]).is_err());
            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, -5.0), 2);
            assert_paints(&painted(tester, painter), &[circle(), circle()]);

            tester.pump_and_settle_by(Duration::from_secs(1));
            assert!(does_not_overscroll(&painted(tester, painter)));
        });
    }

    /// "Overscroll ignored from alternate axis".
    #[test]
    fn an_indicator_ignores_overscrolls_along_the_other_axis() {
        test_widgets(|tester| {
            tester.pump_widget(ltr(ScrollConfiguration::new(
                behavior::<0>(),
                GlowingOverscrollIndicator::new(AxisDirection::Right, Color::new(0xFF0000FF))
                    .child(sized_scroll_view(20.0).physics(always_scrollable())),
            )));
            let painter = custom_paint(tester);
            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, 5.0), 1);
            assert!(does_not_overscroll(&painted(tester, painter)));
            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, -5.0), 2);
            assert!(does_not_overscroll(&painted(tester, painter)));

            tester.pump_and_settle_by(Duration::from_secs(1));
            assert!(does_not_overscroll(&painted(tester, painter)));
        });
    }

    /// "Overscroll horizontally".
    #[test]
    fn a_horizontal_glow_is_rotated_a_quarter_turn() {
        test_widgets(|tester| {
            tester.pump_widget(ltr(sized_scroll_view(20.0)
                .scroll_direction(Axis::Horizontal)
                .physics(always_scrollable())));
            let painter = custom_paint(tester);
            let quarter = std::f64::consts::PI / 2.0;
            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(5.0, 0.0), 1);
            assert_paints(
                &painted(tester, painter),
                &[
                    PaintCall::rotate(Some(quarter)),
                    circle(),
                    PaintCall::SaveRestore,
                ],
            );
            assert!(paints(&painted(tester, painter), &[circle(), circle()]).is_err());
            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(-5.0, 0.0), 2);
            assert_paints(
                &painted(tester, painter),
                &[
                    PaintCall::rotate(Some(quarter)),
                    circle(),
                    PaintCall::rotate(Some(quarter)),
                    circle(),
                ],
            );

            tester.pump_and_settle_by(Duration::from_secs(1));
            assert!(does_not_overscroll(&painted(tester, painter)));
        });
    }

    /// "Nested overscrolls do not throw exceptions".
    #[test]
    fn nested_overscrolls_do_not_throw_exceptions() {
        test_widgets(|tester| {
            tester.pump_widget(ltr(PageView::new().children([ListView::new()
                .children([Container::new()
                    .width(2000.0)
                    .height(2000.0)
                    .color(Color::new(0xFF00FF00))
                    .into_widget()])
                .into_widget()])));

            tester.drag_from(Offset::new(100.0, 100.0), Offset::new(0.0, 2000.0), 1);
            tester.pump_and_settle();
        });
    }

    /// "Changing settings".
    #[test]
    fn a_new_behavior_glows_in_its_own_color() {
        test_widgets(|tester| {
            let quarter = std::f64::consts::PI / 2.0;
            tester.pump_widget(ltr(ScrollConfiguration::new(
                behavior::<0xFF00FF00>(),
                sized_scroll_view(20.0)
                    .scroll_direction(Axis::Horizontal)
                    .physics(always_scrollable())
                    .reverse(true),
            )));
            let painter = custom_paint(tester);
            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(5.0, 0.0), 1);
            assert_paints(
                &painted(tester, painter),
                &[
                    PaintCall::rotate(Some(quarter)),
                    circle_with(None, Some(0x0A00FF00)),
                ],
            );
            assert!(paints(&painted(tester, painter), &[circle(), circle()]).is_err());

            tester.pump_and_settle_by(Duration::from_secs(1));
            tester.pump_widget(ltr(ScrollConfiguration::new(
                behavior::<0xFF0000FF>(),
                sized_scroll_view(20.0)
                    .scroll_direction(Axis::Horizontal)
                    .physics(always_scrollable()),
            )));
            let painter = custom_paint(tester);
            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(5.0, 0.0), 2);
            assert_paints(
                &painted(tester, painter),
                &[
                    PaintCall::rotate(Some(quarter)),
                    circle_with(None, Some(0x0A0000FF)),
                    PaintCall::SaveRestore,
                ],
            );
            assert!(paints(&painted(tester, painter), &[circle(), circle()]).is_err());
        });
    }

    /// A `CustomScrollView` centered on its second sliver of `Text`s: the first sliver's second
    /// item, `First sliver 1`, under `first_sliver_1`, which the tests' `find.text` reads.
    fn centered_scroll_view(first_sliver_1: &GlobalKey) -> WidgetRef {
        let center_key: KeyRef = UniqueKey::new().into();
        let first_sliver_1 = first_sliver_1.clone();
        CustomScrollView::new()
            .center(center_key.clone())
            .physics(always_scrollable())
            .slivers([
                SliverList::builder(move |_app, _context, index| {
                    let item = Text::new(format!("First sliver {index}"));
                    Some(if index == 1 {
                        item.key(first_sliver_1.clone().into()).into_widget()
                    } else {
                        item.into_widget()
                    })
                })
                .item_count(2)
                .into_widget(),
                SliverList::builder(|_app, _context, index| {
                    Some(Text::new(format!("Second sliver {index}")).into_widget())
                })
                .key(center_key)
                .item_count(5)
                .into_widget(),
            ])
            .into_widget()
    }

    /// "CustomScrollView overscroll indicator works if there is sliver before center".
    #[test]
    fn a_glow_over_slivers_before_the_center_starts_at_the_edge() {
        test_widgets(|tester| {
            let first_sliver_1 = GlobalKey::new();
            tester.pump_widget(ltr(ScrollConfiguration::new(
                behavior::<0xFF0000FF>(),
                centered_scroll_view(&first_sliver_1),
            )));

            expect(
                tester,
                &find::by_global_key(&first_sliver_1),
                finds_nothing(),
            );

            slow_drag(
                tester,
                Offset::new(200.0, 200.0),
                Offset::new(0.0, 300.0),
                1,
            );
            expect(
                tester,
                &find::by_global_key(&first_sliver_1),
                finds_one_widget(),
            );
            let painter = custom_paint(tester);
            // The scroll offset and paint extend should cancel out each other.
            assert_paints(
                &painted(tester, painter),
                &[
                    PaintCall::Save,
                    PaintCall::translate(None, Some(0.0)),
                    PaintCall::scale(None, None),
                    circle(),
                ],
            );
        });
    }

    /// "CustomScrollView overscroll indicator works well with [CustomScrollView.center] and
    /// [OverscrollIndicatorNotification.paintOffset]".
    #[test]
    fn a_glow_over_slivers_before_the_center_honors_the_paint_offset() {
        test_widgets(|tester| {
            let first_sliver_1 = GlobalKey::new();
            tester.pump_widget(ltr(ScrollConfiguration::new(
                behavior::<0xFF0000FF>(),
                paint_offset_listener(
                    centered_scroll_view(&first_sliver_1),
                    |leading| leading,
                    50.0,
                ),
            )));

            expect(
                tester,
                &find::by_global_key(&first_sliver_1),
                finds_nothing(),
            );

            // offset will be magnified ten times
            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, 5.0), 1);
            expect(
                tester,
                &find::by_global_key(&first_sliver_1),
                finds_one_widget(),
            );
            let painter = custom_paint(tester);
            // The OverscrollIndicator should respect the [OverscrollIndicatorNotification.paintOffset] setting.
            assert_paints(
                &painted(tester, painter),
                &[
                    PaintCall::Save,
                    PaintCall::translate(None, Some(50.0)),
                    PaintCall::scale(None, None),
                    circle(),
                ],
            );
        });
    }

    fn translated_glow(y: f64) -> Vec<PaintCall> {
        vec![
            PaintCall::Save,
            PaintCall::translate(None, Some(y)),
            PaintCall::scale(None, None),
            circle(),
        ]
    }

    fn flipped_translated_glow(y: f64) -> Vec<PaintCall> {
        vec![
            PaintCall::scale(None, Some(-1.0)),
            PaintCall::Save,
            PaintCall::translate(None, Some(y)),
            PaintCall::scale(None, None),
            circle(),
        ]
    }

    /// "The OverscrollIndicator should not overflow the scrollable view edge".
    #[test]
    fn a_glow_moves_with_the_content_but_never_past_the_edge() {
        test_widgets(|tester| {
            tester.pump_widget(ltr(paint_offset_listener(
                sized_scroll_view(2000.0).into_widget(),
                // both the leading and trailing indicator have a 50.0 pixels offset.
                |_leading| true,
                50.0,
            )));
            let painter = custom_paint(tester);
            let start = Offset::new(200.0, 200.0);
            slow_drag(tester, start, Offset::new(0.0, 5.0), 1);
            assert_paints(&painted(tester, painter), &translated_glow(50.0));
            // Reverse scroll (30 pixels), and the offset < notification.paintOffset.
            tester.drag_from(start, Offset::new(0.0, -30.0), 2);
            tester.pump();
            // The OverscrollIndicator should move with the CustomScrollView.
            assert_paints(&painted(tester, painter), &translated_glow(50.0 - 30.0));

            // Reverse scroll (30+20 pixels) and offset == notification.paintOffset.
            tester.drag_from(start, Offset::new(0.0, -20.0), 3);
            tester.pump();
            assert_paints(&painted(tester, painter), &translated_glow(50.0 - 50.0));

            // Reverse scroll (30+20+10 pixels) and offset > notification.paintOffset.
            tester.drag_from(start, Offset::new(0.0, -10.0), 4);
            tester.pump();
            // The OverscrollIndicator should not overflow the CustomScrollView's edge.
            assert_paints(&painted(tester, painter), &translated_glow(50.0 - 50.0));

            tester.pump_and_settle(); // Finish the leading indicator.

            // trigger the trailing indicator
            slow_drag(tester, start, Offset::new(0.0, -200.0), 5);
            assert_paints(&painted(tester, painter), &flipped_translated_glow(50.0));

            // Reverse scroll (30 pixels), and the offset < notification.paintOffset.
            tester.drag_from(start, Offset::new(0.0, 30.0), 6);
            tester.pump();
            // The OverscrollIndicator should move with the CustomScrollView.
            assert_paints(
                &painted(tester, painter),
                &flipped_translated_glow(50.0 - 30.0),
            );

            // Reverse scroll (30+20 pixels) and offset == notification.paintOffset.
            tester.drag_from(start, Offset::new(0.0, 20.0), 7);
            tester.pump();
            assert_paints(
                &painted(tester, painter),
                &flipped_translated_glow(50.0 - 50.0),
            );

            // Reverse scroll (30+20+10 pixels) and offset > notification.paintOffset.
            tester.drag_from(start, Offset::new(0.0, 10.0), 8);
            tester.pump();
            // The OverscrollIndicator should not overflow the CustomScrollView's edge.
            assert_paints(
                &painted(tester, painter),
                &flipped_translated_glow(50.0 - 50.0),
            );
        });
    }

    /// "[OverscrollIndicatorNotification.paintOffset] test": "Leading".
    #[test]
    fn the_leading_glow_draws_at_the_paint_offset_a_listener_sets() {
        test_widgets(|tester| {
            tester.pump_widget(ltr(paint_offset_listener(
                sized_scroll_view(2000.0).into_widget(),
                |leading| leading,
                50.0,
            )));
            let painter = custom_paint(tester);
            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, 5.0), 1);
            // The OverscrollIndicator should respect the [OverscrollIndicatorNotification.paintOffset] setting.
            assert_paints(&painted(tester, painter), &translated_glow(50.0));
            // Reverse scroll direction.
            tester.drag_from(Offset::new(200.0, 200.0), Offset::new(0.0, -30.0), 2);
            tester.pump();
            // The OverscrollIndicator should move with the CustomScrollView.
            assert_paints(&painted(tester, painter), &translated_glow(50.0 - 30.0));
        });
    }

    /// "[OverscrollIndicatorNotification.paintOffset] test": "Trailing".
    #[test]
    fn the_trailing_glow_draws_at_the_paint_offset_a_listener_sets() {
        test_widgets(|tester| {
            tester.pump_widget(ltr(paint_offset_listener(
                sized_scroll_view(2000.0).into_widget(),
                |leading| !leading,
                50.0,
            )));
            let painter = custom_paint(tester);
            tester.drag_from(Offset::new(200.0, 200.0), Offset::new(200.0, -10000.0), 1);
            tester.pump();
            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, -5.0), 2);
            // The OverscrollIndicator should respect the [OverscrollIndicatorNotification.paintOffset] setting.
            assert_paints(&painted(tester, painter), &flipped_translated_glow(50.0));
            // Reverse scroll direction.
            tester.drag_from(Offset::new(200.0, 200.0), Offset::new(0.0, 30.0), 3);
            tester.pump();
            // The OverscrollIndicator should move with the CustomScrollView.
            assert_paints(
                &painted(tester, painter),
                &flipped_translated_glow(50.0 - 30.0),
            );
        });
    }

    /// "StretchingOverscrollIndicator does not crash when child is null".
    #[test]
    fn a_stretching_indicator_with_no_child_builds() {
        test_widgets(|tester| {
            tester.pump_widget(ltr(StretchingOverscrollIndicator::new(AxisDirection::Down)));
            expect(
                tester,
                &find::by_type::<StretchEffect>(),
                finds_one_widget(),
            );
        });
    }

    fn list_of_items(count: i32, height: f64) -> WidgetRef {
        ListView::builder(move |_app, _context, _index| {
            Some(SizedBox::new().height(height).into_widget())
        })
        .item_count(count)
        .build()
        .physics(always_scrollable())
        .into_widget()
    }

    /// "StretchingOverscrollIndicator does not crash when disposed mid stretch animation".
    #[test]
    fn a_stretching_indicator_disposed_mid_animation_leaves_nothing_running() {
        test_widgets(|tester| {
            tester.pump_widget(ltr(StretchingOverscrollIndicator::new(AxisDirection::Down)
                .child(list_of_items(20, 100.0))));

            // Fling at the top edge to overscroll, which starts the stretch
            // animation via `StretchController::animate`.
            tester.fling_from(VIEW_CENTER, Offset::new(0.0, 300.0), 1000.0, 1);
            tester.pump(); // Start the fling.
            tester.pump_by(Duration::from_millis(100)); // Let the animation begin.
            assert_ne!(
                stretch_strength(tester),
                0.0,
                "the fling stretches the list"
            );

            // Tear down the widget before the animation completes. This disposes the
            // stretch controller (and its AnimationController) while the animation's
            // completion callback is still pending.
            tester.pump_widget(SizedBox::new().into_widget());
            tester.pump_and_settle();
            expect(tester, &find::by_type::<StretchEffect>(), finds_nothing());
        });
    }

    /// The `AnimationController` each stretch release animates with is freed once the next
    /// release or the animation's end replaces it, as Dart's collector frees it.
    #[test]
    fn a_stretch_controller_frees_each_release_animation_it_replaces() {
        test_widgets(|tester| {
            tester.pump_widget(ltr(StretchingOverscrollIndicator::new(AxisDirection::Down)
                .child(list_of_items(20, 100.0))));
            let release_controller = |tester: &WidgetTester| {
                let element = tester.element(find::by_type::<StretchingOverscrollIndicator>());
                let mut app = tester.cell.borrow_mut();
                let state = element
                    .state_handle::<StretchingOverscrollIndicatorState>(&app)
                    .expect("a mounted StretchingOverscrollIndicator");
                let stretch = state.stretch_controller(&mut app);
                app.get(stretch).controller.handle()
            };

            tester.fling_from(VIEW_CENTER, Offset::new(0.0, 300.0), 1000.0, 1);
            tester.pump();
            tester.pump_by(Duration::from_millis(100));
            let first = release_controller(tester).expect("the fling animates the release");

            // A second fling replaces the release animation before it ends.
            tester.fling_from(VIEW_CENTER, Offset::new(0.0, 300.0), 1000.0, 2);
            tester.pump();
            tester.pump_by(Duration::from_millis(100));
            let second = release_controller(tester).expect("the fling animates the release");
            assert_ne!(first, second);
            tester.cell.checkpoint();
            assert!(
                !tester.cell.borrow().contains(first),
                "the replaced release's"
            );

            tester.pump_and_settle();
            assert!(release_controller(tester).is_none());
            tester.cell.checkpoint();
            assert!(
                !tester.cell.borrow().contains(second),
                "the finished release's"
            );
        });
    }

    /// "GlowingOverscrollIndicator does not crash at zero area".
    #[test]
    fn a_glowing_indicator_lays_out_at_zero_area() {
        test_widgets(|tester| {
            let key = GlobalKey::new();
            tester.pump_widget(ltr(Center::new().child(
                SizedBox::shrink().child(
                    GlowingOverscrollIndicator::new(AxisDirection::Down, Color::new(0xFF112233))
                        .key(key.clone().into()),
                ),
            )));
            let app = tester.cell.borrow();
            let size = key
                .current_context(&app)
                .and_then(|context| context.find_render_object(&app))
                .and_then(|object| object.as_box())
                .expect("the indicator is laid out")
                .size(&app);
            assert_eq!(size, Size::ZERO);
        });
    }

    /// "StretchingOverscrollIndicator does not crash at zero area".
    #[test]
    fn a_stretching_indicator_lays_out_at_zero_area() {
        test_widgets(|tester| {
            let key = GlobalKey::new();
            tester.pump_widget(ltr(Center::new().child(
                SizedBox::shrink().child(
                    StretchingOverscrollIndicator::new(AxisDirection::Down)
                        .key(key.clone().into())
                        .child(ListView::new()),
                ),
            )));
            let app = tester.cell.borrow();
            let size = key
                .current_context(&app)
                .and_then(|context| context.find_render_object(&app))
                .and_then(|object| object.as_box())
                .expect("the indicator is laid out")
                .size(&app);
            assert_eq!(size, Size::ZERO);
        });
    }

    // ---- overscroll_stretch_indicator_test.dart ----

    struct Boxes {
        box1: GlobalKey,
        box2: GlobalKey,
        box3: GlobalKey,
        controller: Ref<ScrollController>,
    }

    impl Boxes {
        fn new(tester: &WidgetTester) -> Boxes {
            Boxes {
                box1: GlobalKey::new(),
                box2: GlobalKey::new(),
                box3: GlobalKey::new(),
                controller: ScrollController::default(&mut tester.cell.borrow_mut()),
            }
        }

        fn origins(&self, tester: &WidgetTester) -> [Offset; 3] {
            [
                origin_of(tester, &self.box1),
                origin_of(tester, &self.box2),
                origin_of(tester, &self.box3),
            ]
        }

        fn offset(&self, tester: &WidgetTester) -> f64 {
            self.controller
                .as_controller()
                .offset(&tester.cell.borrow())
        }

        fn jump_to_max(&self, tester: &WidgetTester) {
            let mut app = tester.cell.borrow_mut();
            let controller = self.controller.as_controller();
            let max = controller.position(&app).max_scroll_extent(&app);
            controller.jump_to(&mut app, max);
        }
    }

    /// The stretch tests' `buildTest` arguments past the keys and the controller.
    struct BuildTest {
        axis: Axis,
        reverse: bool,
        text_direction: TextDirection,
        box_height: f64,
        box_width: f64,
        physics: Option<ScrollPhysicsRef>,
    }

    impl Default for BuildTest {
        fn default() -> BuildTest {
            BuildTest {
                axis: Axis::Vertical,
                reverse: false,
                text_direction: TextDirection::Ltr,
                box_height: 250.0,
                box_width: 300.0,
                physics: None,
            }
        }
    }

    fn no_overscroll_behavior() -> ScrollBehaviorRef {
        ScrollBehaviorRef::new(ScrollBehaviorRef::plain().copy_with().overscroll(false))
    }

    /// The stretch tests' `buildTest`.
    fn build_test(boxes: &Boxes, options: BuildTest) -> WidgetRef {
        let axis_direction = match options.axis {
            Axis::Horizontal => match options.text_direction {
                TextDirection::Rtl => {
                    if options.reverse {
                        AxisDirection::Right
                    } else {
                        AxisDirection::Left
                    }
                }
                TextDirection::Ltr => {
                    if options.reverse {
                        AxisDirection::Left
                    } else {
                        AxisDirection::Right
                    }
                }
            },
            Axis::Vertical => {
                if options.reverse {
                    AxisDirection::Up
                } else {
                    AxisDirection::Down
                }
            }
        };
        let tile = |color: u32, key: &GlobalKey| {
            SliverToBoxAdapter::new()
                .child(
                    Container::new()
                        .color(Color::new(color))
                        .key(key.clone().into())
                        .height(options.box_height)
                        .width(options.box_width),
                )
                .into_widget()
        };
        let mut scroll_view = CustomScrollView::new()
            .reverse(options.reverse)
            .scroll_direction(options.axis)
            .controller(boxes.controller.erase())
            .slivers([
                tile(0xD0FF0000, &boxes.box1),
                tile(0xFFFFFF00, &boxes.box2),
                tile(0xFF6200EA, &boxes.box3),
            ]);
        if let Some(physics) = options.physics {
            scroll_view = scroll_view.physics(physics);
        }
        Directionality::new(
            options.text_direction,
            MediaQuery::new(
                MediaQueryData::new().size(WidgetTester::SIZE),
                ScrollConfiguration::new(
                    no_overscroll_behavior(),
                    StretchingOverscrollIndicator::new(axis_direction).child(scroll_view),
                )
                .into_widget(),
            )
            .into_widget(),
        )
        .into_widget()
    }

    fn assert_one_stretching_indicator(tester: &WidgetTester) {
        expect(
            tester,
            &find::by_type::<StretchingOverscrollIndicator>(),
            finds_one_widget(),
        );
        expect(
            tester,
            &find::by_type::<GlowingOverscrollIndicator>(),
            finds_nothing(),
        );
    }

    /// "Stretch overscroll will do nothing when axes do not match".
    #[test]
    fn a_stretch_on_the_other_axis_does_nothing() {
        test_widgets(|tester| {
            let boxes = Boxes::new(tester);
            tester.pump_widget(ltr(MediaQuery::new(
                MediaQueryData::new().size(WidgetTester::SIZE),
                ScrollConfiguration::new(
                    no_overscroll_behavior(),
                    StretchingOverscrollIndicator::new(AxisDirection::Right).child(
                        CustomScrollView::new()
                            .controller(boxes.controller.erase())
                            .slivers([
                                SliverToBoxAdapter::new()
                                    .child(
                                        Container::new()
                                            .color(Color::new(0xD0FF0000))
                                            .key(boxes.box1.clone().into())
                                            .height(250.0),
                                    )
                                    .into_widget(),
                                SliverToBoxAdapter::new()
                                    .child(
                                        Container::new()
                                            .color(Color::new(0xFFFFFF00))
                                            .key(boxes.box2.clone().into())
                                            .height(250.0)
                                            .width(300.0),
                                    )
                                    .into_widget(),
                            ]),
                    ),
                )
                .into_widget(),
            )
            .into_widget()));

            assert_one_stretching_indicator(tester);
            assert_eq!(boxes.offset(tester), 0.0);
            assert_eq!(origin_of(tester, &boxes.box1), Offset::ZERO);
            assert_eq!(origin_of(tester, &boxes.box2), Offset::new(0.0, 250.0));

            let mut gesture = TestPointer::touch(1);
            tester.down(&mut gesture, VIEW_CENTER);
            // Overscroll the start, no stretching occurs.
            tester.move_by(&mut gesture, Offset::new(0.0, 200.0), true);
            tester.pump_and_settle();
            assert_eq!(origin_of(tester, &boxes.box1), Offset::ZERO);
            assert_eq!(origin_of(tester, &boxes.box2).dy(), 250.0);

            tester.up(&gesture);
            tester.pump_and_settle();

            // Overscroll released
            assert_eq!(origin_of(tester, &boxes.box1), Offset::ZERO);
            assert_eq!(origin_of(tester, &boxes.box2), Offset::new(0.0, 250.0));
        });
    }

    /// "Stretch overscroll vertically".
    #[test]
    fn a_vertical_stretch_pulls_the_boxes_apart_at_either_end_and_releases() {
        test_widgets(|tester| {
            let boxes = Boxes::new(tester);
            tester.pump_widget(build_test(&boxes, BuildTest::default()));

            assert_one_stretching_indicator(tester);
            assert_eq!(boxes.offset(tester), 0.0);
            assert_eq!(
                boxes.origins(tester),
                [
                    Offset::ZERO,
                    Offset::new(0.0, 250.0),
                    Offset::new(0.0, 500.0)
                ]
            );

            let mut gesture = TestPointer::touch(1);
            tester.down(&mut gesture, VIEW_CENTER);
            // Overscroll the start
            tester.move_by(&mut gesture, Offset::new(0.0, 200.0), true);
            tester.pump_and_settle();
            let [box1, box2, box3] = boxes.origins(tester);
            assert_eq!(box1, Offset::ZERO);
            assert!(box2.dy() > 255.0, "{box2:?}");
            assert!(box3.dy() > 510.0, "{box3:?}");

            tester.up(&gesture);
            tester.pump_and_settle();

            // Stretch released back to the start
            assert_eq!(
                boxes.origins(tester),
                [
                    Offset::ZERO,
                    Offset::new(0.0, 250.0),
                    Offset::new(0.0, 500.0)
                ]
            );

            // Jump to end of the list
            boxes.jump_to_max(tester);
            tester.pump_and_settle();
            assert_eq!(boxes.offset(tester), 150.0);
            let [box1, box2, box3] = boxes.origins(tester);
            assert_eq!(box1.dy(), -150.0);
            assert_eq!(box2.dy(), 100.0);
            assert_eq!(box3.dy(), 350.0);

            let mut gesture = TestPointer::touch(2);
            tester.down(&mut gesture, VIEW_CENTER);
            // Overscroll the end
            tester.move_by(&mut gesture, Offset::new(0.0, -200.0), true);
            tester.pump_and_settle();
            let [box1, box2, box3] = boxes.origins(tester);
            assert!(box1.dy() < -165.0, "{box1:?}");
            assert!(box2.dy() < 90.0, "{box2:?}");
            assert!(box3.dy() < 350.0, "{box3:?}");

            tester.up(&gesture);
            tester.pump_and_settle();

            // Stretch released back
            let [box1, box2, box3] = boxes.origins(tester);
            assert_eq!(box1.dy(), -150.0);
            assert_eq!(box2.dy(), 100.0);
            assert_eq!(box3.dy(), 350.0);
        });
    }

    /// "Stretch overscroll works in reverse - vertical".
    #[test]
    fn a_reversed_vertical_stretch_pulls_the_boxes_up() {
        test_widgets(|tester| {
            let boxes = Boxes::new(tester);
            tester.pump_widget(build_test(
                &boxes,
                BuildTest {
                    reverse: true,
                    ..BuildTest::default()
                },
            ));

            assert_one_stretching_indicator(tester);
            assert_eq!(boxes.offset(tester), 0.0);
            assert_eq!(
                boxes.origins(tester),
                [
                    Offset::new(0.0, 350.0),
                    Offset::new(0.0, 100.0),
                    Offset::new(0.0, -150.0)
                ]
            );

            let mut gesture = TestPointer::touch(1);
            tester.down(&mut gesture, VIEW_CENTER);
            // Overscroll
            tester.move_by(&mut gesture, Offset::new(0.0, -200.0), true);
            tester.pump_and_settle();
            let [box1, box2, box3] = boxes.origins(tester);
            assert!(box1.dy() < 350.0, "{box1:?}");
            assert!(box2.dy() < 100.0, "{box2:?}");
            assert!(box3.dy() < -150.0, "{box3:?}");
        });
    }

    /// "Stretch overscroll works in reverse - horizontal".
    #[test]
    fn a_reversed_horizontal_stretch_pulls_the_boxes_left() {
        test_widgets(|tester| {
            let boxes = Boxes::new(tester);
            tester.pump_widget(build_test(
                &boxes,
                BuildTest {
                    axis: Axis::Horizontal,
                    reverse: true,
                    ..BuildTest::default()
                },
            ));

            assert_one_stretching_indicator(tester);
            assert_eq!(boxes.offset(tester), 0.0);
            assert_eq!(
                boxes.origins(tester),
                [
                    Offset::new(500.0, 0.0),
                    Offset::new(200.0, 0.0),
                    Offset::new(-100.0, 0.0)
                ]
            );

            let mut gesture = TestPointer::touch(1);
            tester.down(&mut gesture, VIEW_CENTER);
            // Overscroll
            tester.move_by(&mut gesture, Offset::new(-200.0, 0.0), true);
            tester.pump_and_settle();
            let [box1, box2, box3] = boxes.origins(tester);
            assert!(box1.dx() < 500.0, "{box1:?}");
            assert!(box2.dx() < 200.0, "{box2:?}");
            assert!(box3.dx() < -100.0, "{box3:?}");
        });
    }

    /// The horizontal stretch at both ends that "Stretch overscroll horizontally" and
    /// "Stretch overscroll works in reverse - horizontal - RTL" share.
    fn horizontal_stretch_at_both_ends(tester: &mut WidgetTester, options: BuildTest) {
        let boxes = Boxes::new(tester);
        tester.pump_widget(build_test(&boxes, options));

        assert_one_stretching_indicator(tester);
        assert_eq!(boxes.offset(tester), 0.0);
        assert_eq!(
            boxes.origins(tester),
            [
                Offset::ZERO,
                Offset::new(300.0, 0.0),
                Offset::new(600.0, 0.0)
            ]
        );

        let mut gesture = TestPointer::touch(2);
        tester.down(&mut gesture, VIEW_CENTER);
        // Overscroll the start
        tester.move_by(&mut gesture, Offset::new(200.0, 0.0), true);
        tester.pump_and_settle();
        let [box1, box2, box3] = boxes.origins(tester);
        assert_eq!(box1, Offset::ZERO);
        assert!(box2.dx() > 305.0, "{box2:?}");
        assert!(box3.dx() > 610.0, "{box3:?}");

        tester.up(&gesture);
        tester.pump_and_settle();

        // Stretch released back to the start
        assert_eq!(
            boxes.origins(tester),
            [
                Offset::ZERO,
                Offset::new(300.0, 0.0),
                Offset::new(600.0, 0.0)
            ]
        );

        // Jump to end of the list
        boxes.jump_to_max(tester);
        tester.pump_and_settle();
        assert_eq!(boxes.offset(tester), 100.0);
        let [box1, box2, box3] = boxes.origins(tester);
        assert_eq!(box1.dx(), -100.0);
        assert_eq!(box2.dx(), 200.0);
        assert_eq!(box3.dx(), 500.0);

        let mut gesture = TestPointer::touch(3);
        tester.down(&mut gesture, VIEW_CENTER);
        // Overscroll the end
        tester.move_by(&mut gesture, Offset::new(-200.0, 0.0), true);
        tester.pump_and_settle();
        let [box1, box2, box3] = boxes.origins(tester);
        assert!(box1.dx() < -116.0, "{box1:?}");
        assert!(box2.dx() < 190.0, "{box2:?}");
        assert!(box3.dx() < 500.0, "{box3:?}");

        tester.up(&gesture);
        tester.pump_and_settle();

        // Stretch released back
        let [box1, box2, box3] = boxes.origins(tester);
        assert_eq!(box1.dx(), -100.0);
        assert_eq!(box2.dx(), 200.0);
        assert_eq!(box3.dx(), 500.0);
    }

    /// "Stretch overscroll works in reverse - horizontal - RTL".
    #[test]
    fn a_reversed_right_to_left_stretch_pulls_the_boxes_apart_at_either_end() {
        test_widgets(|tester| {
            horizontal_stretch_at_both_ends(
                tester,
                BuildTest {
                    axis: Axis::Horizontal,
                    reverse: true,
                    text_direction: TextDirection::Rtl,
                    ..BuildTest::default()
                },
            )
        });
    }

    /// "Stretch overscroll horizontally".
    #[test]
    fn a_horizontal_stretch_pulls_the_boxes_apart_at_either_end_and_releases() {
        test_widgets(|tester| {
            horizontal_stretch_at_both_ends(
                tester,
                BuildTest {
                    axis: Axis::Horizontal,
                    ..BuildTest::default()
                },
            )
        });
    }

    /// "Stretch overscroll only uses image filter during stretch effect".
    #[test]
    fn a_stretch_filters_its_child_only_while_it_stretches() {
        test_widgets(|tester| {
            let boxes = Boxes::new(tester);
            tester.pump_widget(build_test(
                &boxes,
                BuildTest {
                    axis: Axis::Horizontal,
                    ..BuildTest::default()
                },
            ));

            assert!(!has_image_filter_layer(tester));

            let mut gesture = TestPointer::touch(1);
            tester.down(&mut gesture, VIEW_CENTER);
            // Overscroll
            tester.move_by(&mut gesture, Offset::new(200.0, 0.0), true);
            tester.pump_and_settle();

            assert!(has_image_filter_layer(tester));
        });
    }

    /// "Stretch overscroll horizontally RTL".
    #[test]
    fn a_right_to_left_stretch_pulls_the_boxes_left() {
        test_widgets(|tester| {
            let boxes = Boxes::new(tester);
            tester.pump_widget(build_test(
                &boxes,
                BuildTest {
                    axis: Axis::Horizontal,
                    text_direction: TextDirection::Rtl,
                    ..BuildTest::default()
                },
            ));

            assert_one_stretching_indicator(tester);
            assert_eq!(boxes.offset(tester), 0.0);
            assert_eq!(
                boxes.origins(tester),
                [
                    Offset::new(500.0, 0.0),
                    Offset::new(200.0, 0.0),
                    Offset::new(-100.0, 0.0)
                ]
            );

            let mut gesture = TestPointer::touch(1);
            tester.down(&mut gesture, VIEW_CENTER);
            // Overscroll
            tester.move_by(&mut gesture, Offset::new(-200.0, 0.0), true);
            tester.pump_and_settle();
            let [box1, box2, box3] = boxes.origins(tester);
            assert!(box1.dx() < 500.0, "{box1:?}");
            assert!(box2.dx() < 200.0, "{box2:?}");
            assert!(box3.dx() < -100.0, "{box3:?}");
        });
    }

    /// A listener that counts the confirmations and disallows them while `disallow` is set.
    fn counting_listener(
        child: WidgetRef,
        count: &Rc<Cell<u32>>,
        disallow: &Rc<Cell<bool>>,
    ) -> WidgetRef {
        let count = Rc::clone(count);
        let disallow = Rc::clone(disallow);
        NotificationListener::<OverscrollIndicatorNotification>::new(child)
            .on_notification(move |_app, notification| {
                if disallow.get() {
                    notification.disallow_indicator();
                }
                count.set(count.get() + 1);
                false
            })
            .into_widget()
    }

    /// "Disallow stretching overscroll".
    #[test]
    fn a_disallowed_stretch_leaves_the_boxes_in_place() {
        test_widgets(|tester| {
            let boxes = Boxes::new(tester);
            let indicator_notification = Rc::new(Cell::new(0));
            tester.pump_widget(counting_listener(
                build_test(&boxes, BuildTest::default()),
                &indicator_notification,
                &Rc::new(Cell::new(true)),
            ));

            assert_one_stretching_indicator(tester);
            assert_eq!(indicator_notification.get(), 0);
            assert_eq!(boxes.offset(tester), 0.0);
            assert_eq!(
                boxes.origins(tester),
                [
                    Offset::ZERO,
                    Offset::new(0.0, 250.0),
                    Offset::new(0.0, 500.0)
                ]
            );

            let mut gesture = TestPointer::touch(1);
            tester.down(&mut gesture, VIEW_CENTER);
            // Overscroll the start, should not stretch
            tester.move_by(&mut gesture, Offset::new(0.0, 200.0), true);
            tester.pump_and_settle();
            assert_eq!(indicator_notification.get(), 1);
            assert_eq!(
                boxes.origins(tester),
                [
                    Offset::ZERO,
                    Offset::new(0.0, 250.0),
                    Offset::new(0.0, 500.0)
                ]
            );

            tester.up(&gesture);
            tester.pump_and_settle();
        });
    }

    /// "Disallow stretching overscroll during a fling".
    #[test]
    fn a_disallowed_stretch_does_not_absorb_a_fling() {
        test_widgets(|tester| {
            let boxes = Boxes::new(tester);
            let indicator_notification = Rc::new(Cell::new(0));
            tester.pump_widget(counting_listener(
                build_test(&boxes, BuildTest::default()),
                &indicator_notification,
                &Rc::new(Cell::new(true)),
            ));

            assert_one_stretching_indicator(tester);
            assert_eq!(indicator_notification.get(), 0);

            boxes.jump_to_max(tester);
            tester.pump();

            {
                let mut app = tester.cell.borrow_mut();
                let position = boxes.controller.as_controller().position(&app);
                let drag =
                    position.drag(&mut app, DragStartDetails::default(), Listener::new(|_| {}));
                drag.update(
                    &mut app,
                    DragUpdateDetails::new(
                        Offset::ZERO,
                        None,
                        None,
                        Offset::new(0.0, -5000.0),
                        Some(-5000.0),
                        None,
                    ),
                );
                drag.end(
                    &mut app,
                    DragEndDetails::new(
                        Offset::ZERO,
                        None,
                        Velocity {
                            pixels_per_second: Offset::new(0.0, -5000.0),
                        },
                        Some(-5000.0),
                    ),
                );
            }
            tester.pump();
            tester.pump_by(Duration::from_millis(16));

            assert_eq!(indicator_notification.get(), 1);
            assert_eq!(stretch_strength(tester), 0.0);
        });
    }

    /// "Disallowed stretch does not persist into a new scroll sequence".
    #[test]
    fn a_disallowed_stretch_is_allowed_again_in_the_next_scroll() {
        test_widgets(|tester| {
            let boxes = Boxes::new(tester);
            let indicator_notification = Rc::new(Cell::new(0));
            let disallow_stretch = Rc::new(Cell::new(true));
            tester.pump_widget(counting_listener(
                build_test(&boxes, BuildTest::default()),
                &indicator_notification,
                &disallow_stretch,
            ));

            assert_one_stretching_indicator(tester);
            assert_eq!(indicator_notification.get(), 0);

            let mut disallowed_gesture = TestPointer::touch(1);
            tester.down(&mut disallowed_gesture, VIEW_CENTER);
            tester.move_by(&mut disallowed_gesture, Offset::new(0.0, 200.0), true);
            tester.pump_and_settle();
            tester.up(&disallowed_gesture);
            tester.pump_and_settle();

            assert_eq!(indicator_notification.get(), 1);
            assert_eq!(stretch_strength(tester), 0.0);

            disallow_stretch.set(false);
            {
                let mut app = tester.cell.borrow_mut();
                let controller = boxes.controller.as_controller();
                let max = controller.position(&app).max_scroll_extent(&app);
                controller.jump_to(&mut app, max / 2.0);
            }
            tester.pump();

            tester.fling_from(VIEW_CENTER, Offset::new(0.0, -50.0), 10000.0, 2);
            tester.pump_by(Duration::from_millis(100));
            tester.pump_by(Duration::from_millis(100));
            tester.pump_by(Duration::from_millis(100));

            assert_eq!(indicator_notification.get(), 2);
            assert_ne!(stretch_strength(tester), 0.0);
        });
    }

    /// The `Text('Index $index')` items the bounds tests list.
    fn padded_items() -> WidgetRef {
        ListView::builder(|_app, _context, index| {
            Some(
                Padding::new(EdgeInsetsGeometry::all(10.0))
                    .child(Text::new(format!("Index {index}")))
                    .into_widget(),
            )
        })
        .item_count(20)
        .into_widget()
    }

    /// The column of the bounds tests: a 300-pixel list over a half-transparent box.
    fn list_over_box(clip_behavior: Option<Clip>) -> WidgetRef {
        let mut indicator = StretchingOverscrollIndicator::new(AxisDirection::Down)
            .child(SizedBox::new().height(300.0).child(padded_items()));
        if let Some(clip_behavior) = clip_behavior {
            indicator = indicator.clip_behavior(clip_behavior);
        }
        ltr(MediaQuery::new(
            MediaQueryData::new().size(WidgetTester::SIZE),
            ScrollConfiguration::new(
                no_overscroll_behavior(),
                Column::new().children([
                    indicator.into_widget(),
                    Opacity::new(0.5)
                        .child(Container::new().color(Color::new(0xD0FF0000)).height(100.0))
                        .into_widget(),
                ]),
            )
            .into_widget(),
        )
        .into_widget())
    }

    /// "Stretch does not overflow bounds of container".
    #[test]
    fn a_stretched_list_stays_in_its_container() {
        test_widgets(|tester| {
            tester.pump_widget(list_over_box(None));

            expect(tester, &find::text("Index 1"), finds_one_widget());
            assert_eq!(tester.get_center(find::text("Index 1")).dy(), 51.0);

            let mut gesture = TestPointer::touch(1);
            tester.down(&mut gesture, tester.get_center(find::text("Index 1")));
            // Overscroll the start.
            tester.move_by(&mut gesture, Offset::new(0.0, 200.0), true);
            tester.pump_and_settle();
            expect(tester, &find::text("Index 1"), finds_one_widget());
            assert!(tester.get_center(find::text("Index 1")).dy() > 0.0);
            // In place of Flutter's golden, which shows the text not overlapping the red area below
            // the list: the stretch clips to the list's 300 pixels.
            assert_eq!(
                first_clip_rect(tester),
                Rect::from_ltwh(0.0, 0.0, 800.0, 300.0)
            );
            assert_eq!(first_clip_behavior(tester), Clip::HardEdge);

            tester.up(&gesture);
            tester.pump_and_settle();
        });
    }

    /// "Clip behavior is updated as needed".
    #[test]
    fn a_stretch_clips_only_while_it_stretches_a_viewport_smaller_than_the_screen() {
        test_widgets(|tester| {
            tester.pump_widget(list_over_box(None));

            expect(tester, &find::text("Index 1"), finds_one_widget());
            assert_eq!(tester.get_center(find::text("Index 1")).dy(), 51.0);
            // Currently not clipping
            assert_eq!(first_clip_behavior(tester), Clip::None);

            let mut gesture = TestPointer::touch(1);
            tester.down(&mut gesture, tester.get_center(find::text("Index 1")));
            // Overscroll the start.
            tester.move_by(&mut gesture, Offset::new(0.0, 200.0), true);
            tester.pump_and_settle();
            expect(tester, &find::text("Index 1"), finds_one_widget());
            assert!(tester.get_center(find::text("Index 1")).dy() > 0.0);
            // Now clipping
            assert_eq!(first_clip_behavior(tester), Clip::HardEdge);

            tester.up(&gesture);
            tester.pump_and_settle();
        });
    }

    /// "clipBehavior parameter updates overscroll clipping behavior".
    #[test]
    fn a_stretch_clips_with_the_clip_behavior_it_is_given() {
        test_widgets(|tester| {
            tester.pump_widget(list_over_box(Some(Clip::None)));

            expect(tester, &find::text("Index 1"), finds_one_widget());
            assert_eq!(tester.get_center(find::text("Index 1")).dy(), 51.0);
            // Currently not clipping
            assert_eq!(first_clip_behavior(tester), Clip::None);

            let mut gesture = TestPointer::touch(1);
            tester.down(&mut gesture, tester.get_center(find::text("Index 1")));
            // Overscroll the start.
            tester.move_by(&mut gesture, Offset::new(0.0, 200.0), true);
            tester.pump_and_settle();
            expect(tester, &find::text("Index 1"), finds_one_widget());
            assert!(tester.get_center(find::text("Index 1")).dy() > 0.0);
            // Now clipping
            assert_eq!(first_clip_behavior(tester), Clip::None);

            tester.up(&gesture);
            tester.pump_and_settle();
        });
    }

    /// The stretch limit tests' tree: the 300-pixel list alone, under a default
    /// `MediaQueryData`.
    fn list_alone() -> WidgetRef {
        ltr(MediaQuery::new(
            MediaQueryData::new(),
            ScrollConfiguration::new(
                no_overscroll_behavior(),
                StretchingOverscrollIndicator::new(AxisDirection::Down)
                    .child(SizedBox::new().height(300.0).child(padded_items())),
            )
            .into_widget(),
        )
        .into_widget())
    }

    /// "Stretch limit".
    #[test]
    fn a_stretch_stops_at_its_limit() {
        test_widgets(|tester| {
            tester.pump_widget(list_alone());
            const MAX_STRETCH_LOCATION: f64 = 52.63178407049861;

            expect(tester, &find::text("Index 1"), finds_one_widget());
            assert_eq!(tester.get_center(find::text("Index 1")).dy(), 51.0);

            let mut pointer = TestPointer::touch(1);
            tester.down(&mut pointer, tester.get_center(find::text("Index 1")));
            // Overscroll beyond the limit (the viewport is 600.0).
            tester.move_by(&mut pointer, Offset::new(0.0, 610.0), true);
            tester.pump_and_settle();
            expect(tester, &find::text("Index 1"), finds_one_widget());
            // Within f32: the stretch is an f32 `Matrix4`, where Dart compares exactly.
            assert_f32_equals(
                tester.get_center(find::text("Index 1")).dy(),
                MAX_STRETCH_LOCATION,
            );

            let mut pointer = TestPointer::touch(2);
            tester.down(&mut pointer, tester.get_center(find::text("Index 1")));
            // Overscroll way way beyond the limit
            tester.move_by(&mut pointer, Offset::new(0.0, 1000.0), true);
            tester.pump_and_settle();
            expect(tester, &find::text("Index 1"), finds_one_widget());
            // Within f32: the stretch is an f32 `Matrix4`, where Dart compares exactly.
            assert_f32_equals(
                tester.get_center(find::text("Index 1")).dy(),
                MAX_STRETCH_LOCATION,
            );

            tester.up(&pointer);
            tester.pump_and_settle();
        });
    }

    /// "Multiple pointers will not exceed stretch limit".
    #[test]
    fn more_pointers_do_not_stretch_past_the_limit() {
        test_widgets(|tester| {
            tester.pump_widget(list_alone());
            expect(tester, &find::text("Index 1"), finds_one_widget());
            assert_eq!(tester.get_center(find::text("Index 1")).dy(), 51.0);

            let mut pointer1 = TestPointer::touch(1);
            tester.down(&mut pointer1, tester.get_center(find::text("Index 1")));
            // Overscroll the start.
            tester.move_by(&mut pointer1, Offset::new(0.0, 210.0), true);
            tester.pump_and_settle();
            expect(tester, &find::text("Index 1"), finds_one_widget());
            let mut last_stretched_location = tester.get_center(find::text("Index 1")).dy();
            assert!(last_stretched_location > 51.0);

            let mut pointer2 = TestPointer::touch(2);
            tester.down(&mut pointer2, tester.get_center(find::text("Index 1")));
            // Add overscroll from an additional pointer
            tester.move_by(&mut pointer2, Offset::new(0.0, 210.0), true);
            tester.pump_and_settle();
            expect(tester, &find::text("Index 1"), finds_one_widget());
            assert!(tester.get_center(find::text("Index 1")).dy() > last_stretched_location);
            last_stretched_location = tester.get_center(find::text("Index 1")).dy();

            let mut pointer3 = TestPointer::touch(3);
            tester.down(&mut pointer3, tester.get_center(find::text("Index 1")));
            // Add overscroll from an additional pointer, exceeding the max stretch (600)
            tester.move_by(&mut pointer3, Offset::new(0.0, 210.0), true);
            tester.pump_and_settle();
            expect(tester, &find::text("Index 1"), finds_one_widget());
            assert!(tester.get_center(find::text("Index 1")).dy() > last_stretched_location);
            last_stretched_location = tester.get_center(find::text("Index 1")).dy();

            let mut pointer4 = TestPointer::touch(4);
            tester.down(&mut pointer4, tester.get_center(find::text("Index 1")));
            // Since we have maxed out the overscroll, it should not have stretched
            // further, regardless of the number of pointers.
            tester.move_by(&mut pointer4, Offset::new(0.0, 210.0), true);
            tester.pump_and_settle();
            expect(tester, &find::text("Index 1"), finds_one_widget());
            assert_eq!(
                tester.get_center(find::text("Index 1")).dy(),
                last_stretched_location
            );

            tester.up(&pointer1);
            tester.up(&pointer2);
            tester.up(&pointer3);
            tester.up(&pointer4);
            tester.pump_and_settle();
        });
    }

    /// "Stretch overscroll vertically, change direction mid scroll".
    #[test]
    fn a_vertical_stretch_turns_to_the_other_end_when_the_drag_does() {
        test_widgets(|tester| {
            let boxes = Boxes::new(tester);
            tester.pump_widget(build_test(
                &boxes,
                BuildTest {
                    // Setting the `box_height` to 100.0 will make the boxes fit in the
                    // scrollable viewport.
                    box_height: 100.0,
                    // To make the scroll view in the test still scrollable, we need to add
                    // the `AlwaysScrollableScrollPhysics`.
                    physics: Some(always_scrollable()),
                    ..BuildTest::default()
                },
            ));

            assert_one_stretching_indicator(tester);
            assert_eq!(boxes.offset(tester), 0.0);
            assert_eq!(
                boxes.origins(tester),
                [
                    Offset::ZERO,
                    Offset::new(0.0, 100.0),
                    Offset::new(0.0, 200.0)
                ]
            );

            let mut gesture = TestPointer::touch(1);
            tester.down(&mut gesture, VIEW_CENTER);
            // Overscroll the start
            tester.move_by(&mut gesture, Offset::new(0.0, 600.0), true);
            tester.pump_and_settle();

            // The boxes should now be at different locations because of the scaling.
            let [box1, box2, box3] = boxes.origins(tester);
            assert_eq!(box1, Offset::ZERO);
            assert!(box2.dy() > 103.0, "{box2:?}");
            assert!(box3.dy() > 206.0, "{box3:?}");

            // Move the pointer up a miniscule amount to trigger a directional change.
            tester.move_by(&mut gesture, Offset::new(0.0, -20.0), true);
            tester.pump_and_settle();

            // The boxes should remain roughly at the same locations, since the pointer
            // didn't move far.
            let [box1, box2, box3] = boxes.origins(tester);
            assert_eq!(box1, Offset::ZERO);
            assert!(box2.dy() > 103.0, "{box2:?}");
            assert!(box3.dy() > 206.0, "{box3:?}");

            // Now make the pointer overscroll to the end
            tester.move_by(&mut gesture, Offset::new(0.0, -1200.0), true);
            tester.pump_and_settle();

            let [box1, box2, box3] = boxes.origins(tester);
            assert!(box1.dy() < -19.0, "{box1:?}");
            assert!(box2.dy() < 85.0, "{box2:?}");
            assert!(box3.dy() < 188.0, "{box3:?}");

            // Release the pointer
            tester.up(&gesture);
            tester.pump_and_settle();

            // Now the boxes should be back to their original locations.
            assert_eq!(
                boxes.origins(tester),
                [
                    Offset::ZERO,
                    Offset::new(0.0, 100.0),
                    Offset::new(0.0, 200.0)
                ]
            );
        });
    }

    /// "Stretch overscroll horizontally, change direction mid scroll".
    #[test]
    fn a_horizontal_stretch_turns_to_the_other_end_when_the_drag_does() {
        test_widgets(|tester| {
            let boxes = Boxes::new(tester);
            tester.pump_widget(build_test(
                &boxes,
                BuildTest {
                    // Setting the `box_width` to 100.0 will make the boxes fit in the
                    // scrollable viewport.
                    box_width: 100.0,
                    // To make the scroll view in the test still scrollable, we need to add
                    // the `AlwaysScrollableScrollPhysics`.
                    physics: Some(always_scrollable()),
                    axis: Axis::Horizontal,
                    ..BuildTest::default()
                },
            ));

            assert_one_stretching_indicator(tester);
            assert_eq!(boxes.offset(tester), 0.0);
            assert_eq!(
                boxes.origins(tester),
                [
                    Offset::ZERO,
                    Offset::new(100.0, 0.0),
                    Offset::new(200.0, 0.0)
                ]
            );

            let mut gesture = TestPointer::touch(1);
            tester.down(&mut gesture, VIEW_CENTER);
            // Overscroll the start
            tester.move_by(&mut gesture, Offset::new(600.0, 0.0), true);
            tester.pump_and_settle();

            // The boxes should now be at different locations because of the scaling.
            let [box1, box2, box3] = boxes.origins(tester);
            assert_eq!(box1, Offset::ZERO);
            assert!(box2.dx() > 102.0, "{box2:?}");
            assert!(box3.dx() > 205.0, "{box3:?}");

            // Move the pointer up a miniscule amount to trigger a directional change.
            tester.move_by(&mut gesture, Offset::new(-20.0, 0.0), true);
            tester.pump_and_settle();

            // The boxes should remain roughly at the same locations, since the pointer
            // didn't move far.
            let [box1, box2, box3] = boxes.origins(tester);
            assert_eq!(box1, Offset::ZERO);
            assert!(box2.dx() > 102.0, "{box2:?}");
            assert!(box3.dx() > 205.0, "{box3:?}");

            // Now make the pointer overscroll to the end
            tester.move_by(&mut gesture, Offset::new(-1200.0, 0.0), true);
            tester.pump_and_settle();

            let [box1, box2, box3] = boxes.origins(tester);
            assert!(box1.dx() < -19.0, "{box1:?}");
            assert!(box2.dx() < 85.0, "{box2:?}");
            assert!(box3.dx() < 188.0, "{box3:?}");

            // Release the pointer
            tester.up(&gesture);
            tester.pump_and_settle();

            // Now the boxes should be back to their original locations.
            assert_eq!(
                boxes.origins(tester),
                [
                    Offset::ZERO,
                    Offset::new(100.0, 0.0),
                    Offset::new(200.0, 0.0)
                ]
            );
        });
    }

    /// "Fling toward the trailing edge causes stretch toward the leading edge".
    #[test]
    fn a_fling_into_the_trailing_edge_stretches_toward_the_leading_edge() {
        test_widgets(|tester| {
            let boxes = Boxes::new(tester);
            tester.pump_widget(build_test(&boxes, BuildTest::default()));

            assert_one_stretching_indicator(tester);
            assert_eq!(boxes.offset(tester), 0.0);
            assert_eq!(
                boxes.origins(tester),
                [
                    Offset::ZERO,
                    Offset::new(0.0, 250.0),
                    Offset::new(0.0, 500.0)
                ]
            );

            tester.fling_from(VIEW_CENTER, Offset::new(0.0, -50.0), 10000.0, 1);
            tester.pump_by(Duration::from_millis(100));
            tester.pump_by(Duration::from_millis(100));
            tester.pump_by(Duration::from_millis(100));

            // The boxes should now be at different locations because of the scaling.
            assert_eq!(boxes.offset(tester), 150.0);
            let [box1, box2, box3] = boxes.origins(tester);
            assert!(box1.dy() < -160.0, "{box1:?}");
            assert!(box2.dy() < 93.0, "{box2:?}");
            assert!(box3.dy() < 347.0, "{box3:?}");

            tester.pump_and_settle();

            // The boxes should now be at their final position.
            assert_eq!(boxes.offset(tester), 150.0);
            let [box1, box2, box3] = boxes.origins(tester);
            assert_eq!(box1.dy(), -150.0);
            assert_eq!(box2.dy(), 100.0);
            assert_eq!(box3.dy(), 350.0);
        });
    }

    /// "Fling toward the leading edge causes stretch toward the trailing edge".
    #[test]
    fn a_fling_into_the_leading_edge_stretches_toward_the_trailing_edge() {
        test_widgets(|tester| {
            let boxes = Boxes::new(tester);
            tester.pump_widget(build_test(&boxes, BuildTest::default()));

            assert_one_stretching_indicator(tester);
            assert_eq!(boxes.offset(tester), 0.0);
            assert_eq!(
                boxes.origins(tester),
                [
                    Offset::ZERO,
                    Offset::new(0.0, 250.0),
                    Offset::new(0.0, 500.0)
                ]
            );

            // We fling to the trailing edge and let it settle.
            tester.fling_from(VIEW_CENTER, Offset::new(0.0, -50.0), 10000.0, 1);
            tester.pump_and_settle();

            // We are now at the trailing edge
            assert_eq!(boxes.offset(tester), 150.0);
            let [box1, box2, box3] = boxes.origins(tester);
            assert_eq!(box1.dy(), -150.0);
            assert_eq!(box2.dy(), 100.0);
            assert_eq!(box3.dy(), 350.0);

            // Now fling to the leading edge
            tester.fling_from(VIEW_CENTER, Offset::new(0.0, 50.0), 10000.0, 2);
            tester.pump_by(Duration::from_millis(100));
            tester.pump_by(Duration::from_millis(100));
            tester.pump_by(Duration::from_millis(100));
            tester.pump_by(Duration::from_millis(100));

            // The boxes should now be at different locations because of the scaling.
            assert_eq!(boxes.offset(tester), 0.0);
            let [box1, box2, box3] = boxes.origins(tester);
            assert_eq!(box1.dy(), 0.0);
            assert!(box2.dy() > 250.9, "{box2:?}");
            assert!(box3.dy() > 500.9, "{box3:?}");

            tester.pump_and_settle();

            // The boxes should now be at their final position.
            assert_eq!(boxes.offset(tester), 0.0);
            let [box1, box2, box3] = boxes.origins(tester);
            assert_eq!(box1.dy(), 0.0);
            assert_eq!(box2.dy(), 250.0);
            assert_eq!(box3.dy(), 500.0);
        });
    }

    /// "changing scroll direction during recede animation will not change the stretch
    /// direction".
    #[test]
    fn turning_the_drag_while_the_stretch_recedes_keeps_its_direction() {
        test_widgets(|tester| {
            let boxes = Boxes::new(tester);
            tester.pump_widget(build_test(
                &boxes,
                BuildTest {
                    box_height: 205.0,
                    ..BuildTest::default()
                },
            ));

            assert_one_stretching_indicator(tester);

            // Fling to the trailing edge
            tester.fling_from(VIEW_CENTER, Offset::new(0.0, -50.0), 10000.0, 1);
            tester.pump_and_settle();

            let [box1, box2, box3] = boxes.origins(tester);
            assert_eq!(box1.dy(), -15.0);
            assert_eq!(box2.dy(), 190.0);
            assert_eq!(box3.dy(), 395.0);

            let mut gesture = TestPointer::touch(2);
            tester.down(&mut gesture, VIEW_CENTER);
            // Overscroll to the trailing edge
            tester.move_by(&mut gesture, Offset::new(0.0, -200.0), true);
            tester.pump_and_settle();

            let [box1, box2, box3] = boxes.origins(tester);
            assert!(box1.dy() < -25.0, "{box1:?}");
            assert!(box2.dy() < 185.0, "{box2:?}");
            assert!(box3.dy() < 392.0, "{box3:?}");

            // This will trigger the recede animation
            // The y offset of the boxes should be increasing, since the boxes were stretched
            // toward the leading edge.
            tester.move_by(&mut gesture, Offset::new(0.0, 150.0), true);
            tester.pump_by(Duration::from_millis(100));

            // Explicitly check that the stretch strength is not 0.0, since this would probably
            // mean that the stretch direction is wrong.
            assert_ne!(stretch_strength(tester), 0.0);

            tester.up(&gesture);
            tester.pump_by(Duration::from_millis(100));

            // At this point, the stretchStrength should be close to 0.
            assert!(stretch_strength(tester).abs() < 0.01);

            tester.pump_and_settle();

            // The recede animation is done now, we should now be at the leading edge.
            let [box1, box2, box3] = boxes.origins(tester);
            assert_eq!(box1.dy(), 0.0);
            assert_eq!(box2.dy(), 205.0);
            assert_eq!(box3.dy(), 410.0);
        });
    }

    /// The overscroll stretch tests' `_HighFrictionClampingScrollPhysics`.
    #[derive(Debug)]
    struct HighFrictionClampingScrollPhysics {
        parent: Option<ScrollPhysicsRef>,
    }

    impl ScrollPhysics for HighFrictionClampingScrollPhysics {
        fn as_any(&self) -> &dyn std::any::Any {
            self
        }

        fn parent(&self) -> Option<&ScrollPhysicsRef> {
            self.parent.as_ref()
        }

        fn apply_to(&self, ancestor: Option<ScrollPhysicsRef>) -> ScrollPhysicsRef {
            Rc::new(HighFrictionClampingScrollPhysics {
                parent: ScrollPhysicsBase::build_parent(self, ancestor),
            })
        }

        fn create_ballistic_simulation(
            &self,
            position: &dyn ScrollMetrics,
            velocity: f64,
        ) -> Option<Box<dyn Simulation>> {
            Some(Box::new(ClampingScrollSimulation::with_options(
                position.pixels(),
                velocity,
                0.94,
                self.tolerance_for(position),
            )))
        }
    }

    /// "Stretching animation completes after fling under scroll physics with high friction".
    #[test]
    fn a_stretch_settles_after_a_fling_under_high_friction() {
        test_widgets(|tester| {
            let boxes = Boxes::new(tester);
            let overscroll_velocity: Rc<Cell<Option<f64>>> = Rc::default();
            let tree = NotificationListener::<OverscrollNotification>::new(build_test(
                &boxes,
                BuildTest {
                    physics: Some(Rc::new(HighFrictionClampingScrollPhysics { parent: None })),
                    ..BuildTest::default()
                },
            ))
            .on_notification({
                let overscroll_velocity = Rc::clone(&overscroll_velocity);
                move |_app, notification| {
                    overscroll_velocity.set(Some(notification.velocity));
                    false
                }
            })
            .into_widget();
            tester.pump_widget(tree);

            assert_one_stretching_indicator(tester);
            assert_eq!(boxes.offset(tester), 0.0);
            assert_eq!(
                boxes.origins(tester),
                [
                    Offset::ZERO,
                    Offset::new(0.0, 250.0),
                    Offset::new(0.0, 500.0)
                ]
            );

            // We fling to the trailing edge and let it settle.
            tester.fling_from(VIEW_CENTER, Offset::new(0.0, -50.0), 10000.0, 1);
            tester.pump_and_settle_by(Duration::from_millis(300));

            // We are now at the trailing edge
            assert!(overscroll_velocity.get().expect("an overscroll") < 25.0);
            assert_eq!(boxes.offset(tester), 150.0);
            let [box1, box2, box3] = boxes.origins(tester);
            assert_eq!(box1.dy(), -150.0);
            assert_eq!(box2.dy(), 100.0);
            assert_eq!(box3.dy(), 350.0);
        });
    }

    /// "Fling overscroll triggers stretching animation correctly".
    #[test]
    fn a_short_fling_into_the_edge_keeps_stretching_after_it_ends() {
        test_widgets(|tester| {
            let boxes = Boxes::new(tester);
            let tree = build_test(&boxes, BuildTest::default());
            tester.pump_widget(tree.clone());

            assert_one_stretching_indicator(tester);
            assert_eq!(boxes.offset(tester), 0.0);
            assert_eq!(
                boxes.origins(tester),
                [
                    Offset::ZERO,
                    Offset::new(0.0, 250.0),
                    Offset::new(0.0, 500.0)
                ]
            );

            // Simulates a fast and short user fling.
            tester.fling_from(VIEW_CENTER, Offset::new(0.0, 50.0), 1000.0, 1);

            // Records the current stretch strength of the StretchEffect widget
            // before pumping additional frames, so it can be compared later
            // to verify that the stretch increases after the fling.
            let progress_strength = stretch_strength(tester);

            tester.pump_frames(tree, Duration::from_millis(50));

            // Verifies that the stretchStrength has increased compared to the
            // previously recorded value, ensuring the fling triggers stretching.
            assert!(stretch_strength(tester) > progress_strength);

            tester.pump_and_settle();
            assert_eq!(stretch_strength(tester).abs(), 0.0);
        });
    }

    /// "Fling overscroll triggers stretching animation correctly in reverse".
    #[test]
    fn a_short_fling_into_the_reversed_edge_keeps_stretching_after_it_ends() {
        test_widgets(|tester| {
            let boxes = Boxes::new(tester);
            let tree = build_test(
                &boxes,
                BuildTest {
                    reverse: true,
                    ..BuildTest::default()
                },
            );
            tester.pump_widget(tree.clone());

            assert_one_stretching_indicator(tester);
            assert_eq!(boxes.offset(tester), 0.0);
            assert_eq!(
                boxes.origins(tester),
                [
                    Offset::new(0.0, 350.0),
                    Offset::new(0.0, 100.0),
                    Offset::new(0.0, -150.0)
                ]
            );

            // Simulates a fast and short user fling.
            tester.fling_from(VIEW_CENTER, Offset::new(0.0, -50.0), 1000.0, 1);

            // Records the current stretch strength of the StretchEffect widget
            // before pumping additional frames, so it can be compared later
            // to verify that the stretch increases after the fling.
            let progress_strength = stretch_strength(tester);

            tester.pump_frames(tree, Duration::from_millis(50));

            // Verifies that the stretchStrength has increased compared to the
            // previously recorded value, ensuring the fling triggers stretching.
            assert!(stretch_strength(tester) < progress_strength);

            tester.pump_and_settle();
            assert_eq!(stretch_strength(tester).abs(), 0.0);
        });
    }

    // ---- the notification itself ----

    #[test]
    fn a_confirmation_describes_its_side_and_can_be_disallowed() {
        let notification = OverscrollIndicatorNotification::new(true);
        assert!(notification.accepted.get());
        notification.disallow_indicator();
        assert!(!notification.accepted.get());
        assert_eq!(
            format!("{notification:?}"),
            "OverscrollIndicatorNotification(depth: 0 (local), side: leading edge)"
        );
        assert_eq!(
            format!("{:?}", OverscrollIndicatorNotification::new(false)),
            "OverscrollIndicatorNotification(depth: 0 (local), side: trailing edge)"
        );
    }
}