|
1 | 1 | using System;
|
2 |
| -using System.Collections.Generic; |
| 2 | +using System.Linq; |
3 | 3 |
|
4 | 4 | namespace Microsoft.Maui.Handlers
|
5 | 5 | {
|
6 | 6 | internal static class LayoutExtensions
|
7 | 7 | {
|
8 |
| - record ViewAndIndex(IView View, int Index); |
9 |
| - |
10 |
| - class ZIndexComparer : IComparer<ViewAndIndex> |
11 |
| - { |
12 |
| - public int Compare(ViewAndIndex? x, ViewAndIndex? y) |
13 |
| - { |
14 |
| - if (x == null || y == null) |
15 |
| - { |
16 |
| - return 0; |
17 |
| - } |
18 |
| - |
19 |
| - var zIndexCompare = x.View.ZIndex.CompareTo(y.View.ZIndex); |
20 |
| - |
21 |
| - if (zIndexCompare == 0) |
22 |
| - { |
23 |
| - return x.Index.CompareTo(y.Index); |
24 |
| - } |
25 |
| - |
26 |
| - return zIndexCompare; |
27 |
| - } |
28 |
| - } |
29 |
| - |
30 |
| - static ZIndexComparer s_comparer = new(); |
| 8 | + // <summary> |
| 9 | + // Use this overload if you want to `foreach` over it |
| 10 | + // </summary> |
| 11 | + internal static IOrderedEnumerable<IView> EnumerateByZIndex(this ILayout layout) => layout.OrderBy(v => v.ZIndex); |
31 | 12 |
|
32 | 13 | public static IView[] OrderByZIndex(this ILayout layout)
|
33 | 14 | {
|
34 |
| - var count = layout.Count; |
35 |
| - var indexedViews = new ViewAndIndex[count]; |
36 |
| - |
37 |
| - for (int n = 0; n < count; n++) |
| 15 | + switch (layout.Count) |
38 | 16 | {
|
39 |
| - indexedViews[n] = new ViewAndIndex(layout[n], n); |
| 17 | + case 0: |
| 18 | + return Array.Empty<IView>(); |
| 19 | + case 1: |
| 20 | + return new[] { layout[0] }; |
| 21 | + default: |
| 22 | + return layout.EnumerateByZIndex().ToArray(); |
40 | 23 | }
|
41 |
| - |
42 |
| - Array.Sort(indexedViews, s_comparer); |
43 |
| - |
44 |
| - var ordered = new IView[count]; |
45 |
| - |
46 |
| - for (int n = 0; n < count; n++) |
47 |
| - { |
48 |
| - ordered[n] = indexedViews[n].View; |
49 |
| - } |
50 |
| - |
51 |
| - return ordered; |
52 | 24 | }
|
53 | 25 |
|
54 | 26 | public static int GetLayoutHandlerIndex(this ILayout layout, IView view)
|
55 | 27 | {
|
56 |
| - return layout.OrderByZIndex().IndexOf(view); |
| 28 | + switch (layout.Count) |
| 29 | + { |
| 30 | + case 0: |
| 31 | + return -1; |
| 32 | + case 1: |
| 33 | + return view == layout[0] ? 0 : -1; |
| 34 | + default: |
| 35 | + return layout.EnumerateByZIndex().IndexOf(view); |
| 36 | + } |
57 | 37 | }
|
58 | 38 | }
|
59 | 39 | }
|
0 commit comments