| 31 | } |
| 32 | |
| 33 | export function createWindowStack(options: WindowStackOptions = {}): WindowStack { |
| 34 | const baseZIndex = options.baseZIndex ?? 0; |
| 35 | const step = options.step ?? 1; |
| 36 | let order: string[] = []; |
| 37 | const windowsById = new Map<string, WaylandWindow>(); |
| 38 | const zIndexById = new Map<string, Signal<number>>(); |
| 39 | |
| 40 | const normalize = (window: WaylandWindow): string => { |
| 41 | windowsById.set(window.id, window); |
| 42 | return window.id; |
| 43 | }; |
| 44 | |
| 45 | const uniqueOrder = (nextOrder: string[]): string[] => { |
| 46 | const seen = new Set<string>(); |
| 47 | return nextOrder.filter((id) => { |
| 48 | if (seen.has(id)) { |
| 49 | return false; |
| 50 | } |
| 51 | seen.add(id); |
| 52 | return true; |
| 53 | }); |
| 54 | }; |
| 55 | |
| 56 | const zIndexSignal = (id: string): Signal<number> => { |
| 57 | let existing = zIndexById.get(id); |
| 58 | if (!existing) { |
| 59 | existing = withoutCompositionOwnership(() => signal(baseZIndex)); |
| 60 | zIndexById.set(id, existing); |
| 61 | } |
| 62 | return existing; |
| 63 | }; |
| 64 | |
| 65 | const zIndexForId = (id: string): number => |
| 66 | zIndexById.get(id)?.peek() ?? baseZIndex; |
| 67 | |
| 68 | const edgeZIndex = ( |
| 69 | remaining: readonly string[], |
| 70 | placement: WindowStackPlacement, |
| 71 | ): number => { |
| 72 | if (remaining.length === 0) { |
| 73 | return baseZIndex; |
| 74 | } |
| 75 | const edgeId = |
| 76 | placement === "front" ? remaining[remaining.length - 1] : remaining[0]; |
| 77 | return zIndexForId(edgeId) + (placement === "front" ? step : -step); |
| 78 | }; |
| 79 | |
| 80 | const moveTo = (window: WaylandWindow, placement: WindowStackPlacement): void => { |
| 81 | const id = normalize(window); |
| 82 | const currentIndex = order.indexOf(id); |
| 83 | const targetIndex = placement === "front" ? order.length - 1 : 0; |
| 84 | if (currentIndex >= 0 && currentIndex === targetIndex) { |
| 85 | return; |
| 86 | } |
| 87 | |
| 88 | const without = order.filter((candidate) => candidate !== id); |
| 89 | zIndexSignal(id).set(edgeZIndex(without, placement)); |
| 90 | order = placement === "front" ? [...without, id] : [id, ...without]; |