All files LayerHelper.ts

94.07% Statements 127/135
78.35% Branches 76/97
95% Functions 19/20
98.27% Lines 114/116

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                    27x 27x 27x 27x 27x 27x 27x 27x     27x       10x 10x       7x 7x       25x 25x 25x 25x               25x 23x   23x 1x   23x 1x         16x 16x 16x 15x   14x 14x 14x       2x 2x 2x   1x 1x       5x 5x   5x 5x       6x 6x   4x 4x   4x 4x 4x       42x 1x   42x   42x 3x 3x 3x 3x                   1x 1x   1x 1x 1x 1x 1x                     1x 1x   1x 1x 1x 1x 1x                               41x 39x 39x   5x     5x 5x 2x 2x 2x               5x 5x             62x       21x       1x       21x 21x   21x       21x   21x 21x 21x     21x 4x       17x 2x       15x         21x 3x 1x 1x   1x 1x 1x     1x 1x     3x 2x       21x 21x 4x 4x 17x 3x 14x 2x     21x                                  
import {KeyInfo} from '../../types/Types'
import Portal = IITC.Portal
 
interface InventoryKeyInfo {
    total: number
    atHand?: number
    capsules?: Map<string, number>
}
 
export class LayerHelper {
    private readonly layerGroup = new L.LayerGroup<any>()
    private keys = new Map<string, KeyInfo>()
    private readonly markers = new Map<string, L.Marker>()
    private inventoryLayerSuppressed = false
    private invOrigOnAdded: ((portal: Portal) => void) | undefined = undefined
    private mapEventsRegistered = false
    private displayMode: 'count' | 'icon' = 'count'
    private focusedAgent: string | undefined = undefined
 
    constructor(name: string) {
        window.addLayerGroup(name, this.layerGroup, true)
    }
 
    public setDisplayMode(mode: 'count' | 'icon'): void {
        this.displayMode = mode
        this.refreshMarkers()
    }
 
    public setFocusedAgent(agentName: string | undefined): void {
        this.focusedAgent = agentName
        this.refreshMarkers()
    }
 
    public setKeys(keys: Map<string, KeyInfo>): void {
        this.keys = keys
        this.registerMapLayerEvents()
        this.maybeSupressInventoryLayer()
        this.refreshMarkers()
    }
 
    /**
     * Registers map-level layeradd/layerremove listeners once window.map is ready.
     * These keep the inv plugin markers in sync when the user toggles "Team Keys".
     */
    private registerMapLayerEvents(): void {
        if (this.mapEventsRegistered || !window.map) return
        this.mapEventsRegistered = true
 
        window.map.on('layerremove', (event) => {
            Eif ((event as any).layer === this.layerGroup) this.onTeamLayerHidden()
        })
        window.map.on('layeradd', (event) => {
            Eif ((event as any).layer === this.layerGroup) this.onTeamLayerShown()
        })
    }
 
    public onPortalAdded(portal: Portal): void {
        this.maybeSupressInventoryLayer()
        const guid = portal.options.guid
        if (!this.keys.has(guid)) return
        if (this.markers.has(guid)) return
 
        const marker = this.createMarker(guid)
        this.layerGroup.addLayer(marker)
        this.markers.set(guid, marker)
    }
 
    public onPortalRemoved(portal: Portal): void {
        const guid = portal.options.guid
        const marker = this.markers.get(guid)
        if (!marker) return
 
        this.layerGroup.removeLayer(marker)
        this.markers.delete(guid)
    }
 
    public onPortalSelected(data: any): void {
        const unsel = data.unselectedPortalGuid as string | undefined
        const sel = data.selectedPortalGuid as string | undefined
 
        if (unsel) this.toggleDetails(unsel, false)
        if (sel) this.toggleDetails(sel, true)
    }
 
    private toggleDetails(guid: string, showDetails: boolean): void {
        const existing = this.markers.get(guid)
        if (!existing) return
 
        this.layerGroup.removeLayer(existing)
        this.markers.delete(guid)
 
        const marker = this.createMarker(guid, showDetails)
        this.layerGroup.addLayer(marker)
        this.markers.set(guid, marker)
    }
 
    private refreshMarkers(): void {
        for (const marker of this.markers.values()) {
            this.layerGroup.removeLayer(marker)
        }
        this.markers.clear()
 
        for (const guid of Object.keys(window.portals)) {
            Iif (!this.keys.has(guid)) continue
            const marker = this.createMarker(guid)
            this.layerGroup.addLayer(marker)
            this.markers.set(guid, marker)
        }
    }
 
    /**
     * Called when the "Team Keys" layer is hidden via the layer control.
     * Restores inv plugin markers for team portals currently on screen so
     * the "Portal keys" layer keeps showing personal key counts.
     */
    private onTeamLayerHidden(): void {
        const invLayerHelper = this.getInventoryLayerHelper()
        Iif (!invLayerHelper || !this.invOrigOnAdded) return
 
        for (const guid of Object.keys(window.portals)) {
            Iif (!this.keys.has(guid)) continue
            Eif (invLayerHelper.keys?.has(guid) && !invLayerHelper.markers?.has(guid)) {
                const portal = window.portals[guid]
                Eif (portal) this.invOrigOnAdded(portal)
            }
        }
    }
 
    /**
     * Called when the "Team Keys" layer is shown via the layer control.
     * Removes any inv plugin markers for team portals so the combined marker
     * in the "Team Keys" layer takes over without overlap.
     */
    private onTeamLayerShown(): void {
        const invLayerHelper = this.getInventoryLayerHelper()
        Iif (!invLayerHelper) return
 
        Eif (invLayerHelper.markers instanceof Map) {
            for (const [guid, marker] of invLayerHelper.markers.entries()) {
                Eif (this.keys.has(guid)) {
                    invLayerHelper.layerGroup?.removeLayer(marker)
                    invLayerHelper.markers.delete(guid)
                }
            }
        }
    }
 
    /**
     * When KuKuInventory is installed, suppress its map markers for portals where
     * the team inventory also has data. This prevents two overlapping DivIcon markers
     * at the same coordinates. The team inventory layer then shows a single combined
     * marker with both personal and team key counts.
     *
     * Only runs once (guarded by inventoryLayerSuppressed). Called on every
     * onPortalAdded to handle the case where the inventory plugin loads after init.
     */
    private maybeSupressInventoryLayer(): void {
        if (this.inventoryLayerSuppressed) return
        const invLayerHelper = this.getInventoryLayerHelper()
        if (!invLayerHelper) return
 
        this.inventoryLayerSuppressed = true
 
        // Remove any existing inventory markers that overlap with team portals
        Eif (invLayerHelper.markers instanceof Map) {
            for (const [guid, marker] of invLayerHelper.markers.entries()) {
                Eif (this.keys.has(guid)) {
                    invLayerHelper.layerGroup?.removeLayer(marker)
                    invLayerHelper.markers.delete(guid)
                }
            }
        }
 
        // Save the original method so onTeamLayerHidden can call it directly.
        // Override onPortalAdded: skip inv marker for team portals only when the
        // "Team Keys" layer is active. Arrow function keeps `this.keys` current.
        this.invOrigOnAdded = (invLayerHelper.onPortalAdded as (p: Portal) => void).bind(invLayerHelper)
        invLayerHelper.onPortalAdded = (portal: Portal) => {
            if (this.keys.has(portal.options.guid) && window.map.hasLayer(this.layerGroup)) return
            this.invOrigOnAdded!(portal)
        }
    }
 
    private getInventoryLayerHelper() {
        return window.plugin.KuKuInventory?.layerHelper
    }
 
    private getInventoryKeyInfo(guid: string): InventoryKeyInfo | undefined {
        return this.getInventoryLayerHelper()?.keys?.get(guid) as InventoryKeyInfo | undefined
    }
 
    private getInventoryCapsuleName(key: string): string {
        return window.plugin.KuKuInventory?.capsuleNames?.[key] ?? key
    }
 
    private createMarker(guid: string, withDetails: boolean = false): L.Marker {
        const keyInfo = this.keys.get(guid)
        Iif (!keyInfo) throw new Error(`KeyInfo not found for guid: ${guid}`)
 
        const invInfo = this.getInventoryKeyInfo(guid)
 
        // In icon mode (portal not selected) show an inline SVG key.
        // In count mode, or when the portal is selected (expanded), show the text label.
        const isIconMode = this.displayMode === 'icon' && !withDetails
 
        const hasFocus = this.focusedAgent !== undefined
        const focusedCount = hasFocus ? (keyInfo.agentCounts.get(this.focusedAgent!) ?? 0) : 0
        const agentHasKey = focusedCount > 0
 
        let innerHtml: string
        if (isIconMode) {
            innerHtml = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="14" height="14">'
                + '<path fill="currentColor" d="M12.65 10C11.83 7.67 9.61 6 7 6c-3.31 0-6 2.69-6 6s2.69 6 6 6'
                + 'c2.61 0 4.83-1.67 5.65-4H17v4h4v-4h2v-4H12.65zM7 14c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/>'
                + '</svg>'
        } else if (hasFocus && !withDetails) {
            innerHtml = agentHasKey
                ? `<strong>${focusedCount}</strong>/${keyInfo.total}`
                : `${keyInfo.total}`
        } else {
            innerHtml = invInfo
                ? `${invInfo.total} / <strong>${keyInfo.total}</strong>`
                : `<strong>${keyInfo.total}</strong>`
        }
 
        if (withDetails) {
            if (invInfo) {
                Eif (invInfo.atHand !== undefined) {
                    innerHtml += `<br /><em>Hand: ${invInfo.atHand}</em>`
                }
                Eif (invInfo.capsules?.size) {
                    for (const [capsule, count] of invInfo.capsules) {
                        innerHtml += `<br />${this.getInventoryCapsuleName(capsule)}: ${count}`
                    }
                }
                Eif (keyInfo.agentCounts.size > 0) {
                    innerHtml += '<br />---'
                }
            }
            for (const [agent, count] of keyInfo.agentCounts) {
                innerHtml += `<br />${agent}: ${count}`
            }
        }
 
        let bubbleClass = 'team-key-bubble'
        if (isIconMode) {
            bubbleClass += ' team-key-bubble--icon'
            if (hasFocus) bubbleClass += agentHasKey ? ' team-key-bubble--focused' : ' team-key-bubble--unfocused'
        } else if (withDetails) {
            bubbleClass += ' team-key-bubble--details'
        } else if (hasFocus) {
            bubbleClass += agentHasKey ? ' team-key-bubble--focused' : ' team-key-bubble--unfocused'
        }
 
        return L.marker(
            new L.LatLng(keyInfo.portal.lat, keyInfo.portal.lng),
            {
                icon: new L.DivIcon({
                    html: `<div class="${bubbleClass}">${innerHtml}</div>`,
                    className: 'layer-team-key-info',
                    // Zero-size anchor so Leaflet places the div exactly at the portal
                    // pixel with no offset — the inner bubble centres itself via CSS.
                    iconSize: [0, 0],
                    iconAnchor: [0, 0],
                }),
                interactive: false,
                zIndexOffset: withDetails ? 10000 : 0,
            }
        )
    }
}