/* Tarkov Maps -- every map on one shared canvas. * * The base layer is the overall satellite map, rotated so north is up. Every * detail map is scaled and positioned onto it, so zooming into Customs on the * world map lands you in the full-resolution re3mr Customs map. * * Coordinates: LatLng is (y, x) in *world pixels* at native resolution, where * one world pixel is 1/overallScale of an overall-map pixel. Each map's tiles * are numbered from its own padded cell origin -- see tools/common.py. */ const ZOOM_HEADROOM = 1; // how far past a layer's native detail we allow const ZOOM_SNAP = 0.25; const BLANK = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='; /* --- performance profile ---------------------------------------------- * Two things make the map stutter when you alt-tab to it mid-raid: a weak * device and a slow connection. Both are dominated by how many tiles are in * play, so the profile mostly decides that. 'auto' reads the hardware; * 'fast' and 'sharp' are the user's override (the Detail button). */ const QUALITY_KEY = 'tarkov-quality'; const QUALITY_MODES = ['auto', 'fast', 'sharp']; const storedQuality = localStorage.getItem(QUALITY_KEY); const qualityMode = QUALITY_MODES.includes(storedQuality) ? storedQuality : 'auto'; const connection = navigator.connection ?? {}; const lowEndDevice = (Number(navigator.deviceMemory) || 8) <= 4 || (Number(navigator.hardwareConcurrency) || 8) <= 2; const slowNetwork = connection.saveData === true || /^(slow-2g|2g|3g)$/.test(String(connection.effectiveType ?? '')); const fastMode = qualityMode === 'fast' || (qualityMode === 'auto' && (lowEndDevice || slowNetwork)); /* Leaflet picks its tile level with Math.round(mapZoom), so at zoom 2.25 it * takes level 2 and stretches it 1.19x; on a 1.5x display that compounds to a * visibly soft 1.78x upscale. Halving a tile's CSS size and asking for one * level deeper makes us downscale a denser level instead. * * The boost costs ~4x the tiles in view -- DOM nodes, decodes and bytes -- so * it is reserved for displays that can actually show the extra pixels (DPR * above 1) and for the explicit 'sharp' mode. A 1:1 display accepts at most a * 1.19x stretch at quarter zooms, which is not worth quadrupling the tiles * for on a weak machine or a slow link. */ const DENSITY_BOOST = qualityMode === 'sharp' ? 1 : (!fastMode && window.devicePixelRatio > 1.05 ? 1 : 0); const PERF = { // Tile fade-in is an opacity transition per tile; a weak GPU feels it. fade: !fastMode, // Load tiles when the pan settles, not during it. Leaflet defaults to this // on phones; the low-res underlay keeps the map readable meanwhile. updateWhenIdle: fastMode || L.Browser.mobile, updateInterval: fastMode ? 400 : 200, keepBuffer: fastMode ? 1 : 2, // Pyramid level of the always-resident low-res underlay per detail map. previewLevel: 4, // Deepest level warmed into the cache in the background. precacheLevel: fastMode ? 4 : 5, precache: !slowNetwork, }; const OffsetTileLayer = L.TileLayer.extend({ createTile(coords, done) { const tile = L.TileLayer.prototype.createTile.call(this, coords, done); // Decode off the main thread: a burst of forty WebP decodes at the end of // a pan is a visible hitch on a weak CPU. tile.decoding = 'async'; return tile; }, getTileUrl(coords) { const o = this.options; const perCell = (o.baseTileSize * 2 ** coords.z) / o.tileSize; // ?v= busts the week-long immutable cache when a map is re-tiled; the same // URL would otherwise serve a previous build's imagery. return L.Util.template(this._url, { z: coords.z + o.zoomOffset, x: coords.x - o.cell[0] * perCell, y: coords.y - o.cell[1] * perCell, }) + (o.version ? `?v=${o.version}` : ''); }, }); const rectOf = (m) => L.latLngBounds( [m.origin[1], m.origin[0]], [m.origin[1] + m.size[1], m.origin[0] + m.size[0]], ); const trimPointsOf = (m) => ( Array.isArray(m.trim?.points) && m.trim.points.length >= 3 ? m.trim.points : null ); // The aligned raster keeps its original rectangle, but navigation should use // the portion the trim polygon says is actually playable/visible. const viewRectOf = (m) => { const points = trimPointsOf(m); if (!points) return rectOf(m); const xs = points.map(([x]) => x); const ys = points.map(([, y]) => y); return L.latLngBounds( [m.origin[1] + Math.min(...ys) * m.size[1], m.origin[0] + Math.min(...xs) * m.size[0]], [m.origin[1] + Math.max(...ys) * m.size[1], m.origin[0] + Math.max(...xs) * m.size[0]], ); }; const viewContains = (m, latlng) => { const points = trimPointsOf(m); if (!points) return rectOf(m).contains(latlng); const x = (latlng.lng - m.origin[0]) / m.size[0]; const y = (latlng.lat - m.origin[1]) / m.size[1]; let inside = false; for (let i = 0, j = points.length - 1; i < points.length; j = i, i += 1) { const [xi, yi] = points[i]; const [xj, yj] = points[j]; if ((yi > y) !== (yj > y) && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) { inside = !inside; } } return inside; }; const centerOf = (m) => L.latLng( m.origin[1] + m.size[1] / 2, m.origin[0] + m.size[0] / 2, ); const geometryOf = (m) => ({ center: centerOf(m), width: m.size[0], height: m.size[1], }); const rectAt = (geometry) => L.latLngBounds( [geometry.center.lat - geometry.height / 2, geometry.center.lng - geometry.width / 2], [geometry.center.lat + geometry.height / 2, geometry.center.lng + geometry.width / 2], ); function readHash() { const p = location.hash.replace(/^#/, '').split('/'); if (p.length !== 3) return null; const [z, y, x] = p.map(Number); return [z, y, x].every(Number.isFinite) ? { z, y, x } : null; } async function main() { const [world, markerConfig, capabilities, extractTranslationData] = await Promise.all([ fetch('data/world.json', { cache: 'no-cache' }).then((r) => { if (!r.ok) throw new Error(`world.json: ${r.status}`); return r.json(); }), fetch('data/marker-config.json', { cache: 'no-cache' }) .then((r) => (r.ok ? r.json() : { defaults: {}, groups: [], categories: {} })) .catch(() => ({ defaults: {}, groups: [], categories: {} })), fetch('data/capabilities.json', { cache: 'no-store' }) .then((r) => (r.ok ? r.json() : { editable: false })) .catch(() => ({ editable: false })), fetch('data/extract-translations.zh-CN.json', { cache: 'no-cache' }) .then((r) => (r.ok ? r.json() : { markers: {} })) .catch(() => ({ markers: {} })), ]); if (!world.maps.length) throw new Error('world.json contains no maps'); const mapEditingEnabled = capabilities.mapEditing === true; const markerEditingEnabled = capabilities.markerEditing === true; const markerPersistence = capabilities.markerPersistence === 'server' ? 'server' : 'local'; const exportingEnabled = capabilities.exporting === true; const extractTranslations = extractTranslationData?.markers ?? {}; let language = localStorage.getItem('tarkov-language') === 'zh-CN' ? 'zh-CN' : 'en'; let languageButton = null; let refreshLocalizedMarkers = () => {}; const renderLanguageControl = () => { document.documentElement.lang = language === 'zh-CN' ? 'zh-CN' : 'en'; if (!languageButton) return; languageButton.dataset.language = language; languageButton.innerHTML = language === 'zh-CN' ? 'EN/中文' : 'EN/中文'; languageButton.setAttribute( 'aria-label', language === 'zh-CN' ? 'Switch extract names to English' : '切换撤离点名称为中文', ); }; const ZMAX = world.maxZoom; const base = world.maps.find((m) => m.base) ?? world.maps[0]; const CRS = L.extend({}, L.CRS.Simple, { transformation: new L.Transformation(1, 0, 1, 0), scale: (z) => 2 ** (z - ZMAX), zoom: (s) => Math.log(s) / Math.LN2 + ZMAX, }); const extent = L.latLngBounds([0, 0], [world.worldSize[1], world.worldSize[0]]); const map = L.map('map', { crs: CRS, minZoom: 0, maxZoom: ZMAX + ZOOM_HEADROOM, zoomSnap: ZOOM_SNAP, zoomDelta: 0.5, wheelPxPerZoomLevel: 90, maxBounds: extent.pad(0.05), maxBoundsViscosity: 0.75, fadeAnimation: PERF.fade, attributionControl: false, zoomControl: false, }); // Leaflet stacks bottom-corner controls upwards in insertion order, so the // attribution goes in first to sit flush in the corner, zoom above it. L.control.attribution({ prefix: false }) .addAttribution(world.attribution) .addTo(map); const zoomControl = L.control.zoom({ position: 'bottomright' }).addTo(map); // Leaflet's zoom buttons are , which browsers treat as draggable // links -- a slightly-moving click became a ghost-image link drag. Make them // behave like the plain s in the toolbar. for (const anchor of zoomControl.getContainer().querySelectorAll('a')) { anchor.draggable = false; anchor.addEventListener('dragstart', (event) => event.preventDefault()); } const LanguageControl = L.Control.extend({ options: { position: 'bottomright' }, onAdd() { const container = L.DomUtil.create('div', 'leaflet-bar leaflet-control-language'); languageButton = L.DomUtil.create('button', '', container); languageButton.type = 'button'; L.DomEvent.disableClickPropagation(container); L.DomEvent.on(languageButton, 'click', () => { language = language === 'zh-CN' ? 'en' : 'zh-CN'; localStorage.setItem('tarkov-language', language); renderLanguageControl(); refreshLocalizedMarkers(); }); renderLanguageControl(); return container; }, }); new LanguageControl().addTo(map); const boost = DENSITY_BOOST; /* Stacking. Placements are approximate, so map rectangles overlap even when * the real locations don't (Reserve clips Customs, Lighthouse clips * Shoreline). Baseline order puts the finer map on top: sort by * maxNativeZoom, then by smaller footprint. `focus()` then lifts whichever * map you are actually looking at above the rest, so an overlapping * neighbour can never hide the map you came to see. */ const detail = world.maps.filter((m) => !m.base); const stackOrder = [...detail].sort( (a, b) => (a.maxNativeZoom - b.maxNativeZoom) || (b.size[0] * b.size[1] - a.size[0] * a.size[1]), ); const BASE_Z = 1; const baseZ = new Map(stackOrder.map((m, i) => [m.id, 2 + i])); const TOP_Z = 2 + stackOrder.length; const layers = new Map(); const previewLayers = new Map(); const panes = new Map(); const insideLayers = new Map(); const insidePanes = new Map(); const detailById = new Map(detail.map((m) => [m.id, m])); const previewGeometry = new Map(detail.map((m) => [m.id, geometryOf(m)])); // Maps whose placement preview differs from the saved geometry. Only these // need their pane re-transformed on every move/zoom frame; outside the // placement editor the set is empty and the per-frame handler is free. const movedPreviews = new Set(); const savedTrim = (m) => ({ points: Array.isArray(m.trim?.points) ? m.trim.points.map((p) => [...p]) : [], transparency: Number.isFinite(m.trim?.outsideTransparency) ? m.trim.outsideTransparency : 0.75, }); const paneZ = (id, focused = false) => ( focused ? 600 + TOP_Z * 2 : 300 + baseZ.get(id) * 2 ); let updateMarkerFocus = () => {}; let lastFocusKey = null; const focus = (id) => { const selected = detail.find((m) => m.id === id); const rootId = selected?.parent ?? selected?.id; const family = rootId ? detail.filter((m) => m.id === rootId || m.parent === rootId) : []; // syncUI calls this on every moveend. Re-stacking the same family and // re-fetching its markers each pan is wasted DOM and network work. const key = `${id ?? ''}|${family.map((m) => m.id).join(',')}`; if (key === lastFocusKey) return; lastFocusKey = key; updateMarkerFocus(family.map((m) => m.id)); for (const [mid, pane] of panes) { const familyIndex = family.findIndex((m) => m.id === mid); let z = paneZ(mid); if (familyIndex >= 0) z = 600 + TOP_Z * 2 + familyIndex * 2; // A directly selected child remains the top member of its family. When // the parent is selected, children naturally follow above it. if (selected?.parent && mid === id) z += family.length * 2; pane.style.zIndex = String(z); const inside = insidePanes.get(mid); if (inside) inside.style.zIndex = String(z + 1); } }; const familyViewRect = (m) => { const own = viewRectOf(m); const combined = L.latLngBounds(own.getSouthWest(), own.getNorthEast()); if (!m.parent) { detail.filter((child) => child.parent === m.id) .forEach((child) => combined.extend(viewRectOf(child))); } return combined; }; const updatePreviewTransform = (m) => { const pane = panes.get(m.id); if (!pane) return; const saved = geometryOf(m); const preview = previewGeometry.get(m.id) ?? saved; const scale = 2 ** (map.getZoom() - ZMAX); const dx = (preview.center.lng - saved.center.lng) * scale; const dy = (preview.center.lat - saved.center.lat) * scale; const sx = preview.width / saved.width; const sy = preview.height / saved.height; const identity = dx === 0 && dy === 0 && sx === 1 && sy === 1; if (identity) movedPreviews.delete(m.id); else movedPreviews.add(m.id); const origin = identity ? null : map.latLngToLayerPoint(saved.center); for (const target of [pane, insidePanes.get(m.id)].filter(Boolean)) { if (identity) { target.style.removeProperty('transform-origin'); target.style.removeProperty('transform'); } else { target.style.transformOrigin = `${origin.x}px ${origin.y}px`; target.style.transform = `translate3d(${dx}px, ${dy}px, 0) scale(${sx}, ${sy})`; } } }; const updatePreviewTransforms = () => { for (const id of movedPreviews) updatePreviewTransform(detailById.get(id)); }; const usesPermanentTrim = (m) => !m.base && !!m.trim && !!m.trimmedVersion; const tileUrl = (m, trimmed = false) => ( `${trimmed ? 'tiles-trimmed' : 'tiles'}/${m.id}/{z}/{x}/{y}.webp` ); const tileOptions = (m, paneName, isBase = false, version = m.version) => ({ cell: m.cell, bounds: rectOf(m), pane: isBase ? 'tilePane' : paneName, version, baseTileSize: world.tileSize, tileSize: world.tileSize / 2 ** boost, zoomOffset: boost, minZoom: isBase ? 0 : m.minZoom, maxZoom: ZMAX + ZOOM_HEADROOM, maxNativeZoom: Math.max(0, m.maxNativeZoom - boost), minNativeZoom: 0, noWrap: true, keepBuffer: isBase ? 6 : PERF.keepBuffer, // The base backdrop is a handful of tiles; keep it filling in mid-pan. updateWhenIdle: isBase ? false : PERF.updateWhenIdle, updateInterval: PERF.updateInterval, errorTileUrl: BLANK, zIndex: isBase ? BASE_Z : baseZ.get(m.id), className: isBase ? 'tile-base' : undefined, }); /* Low-res underlay. A detail map's pyramid at z<=4 is a handful of tiles * (Customs: six, ~20 KB) that cover the whole map. Loaded once and kept, * they paint wherever the full-res tiles have not arrived yet -- a fresh * deep-link load, or a quick pan into new ground -- so the map reads as * "blurry, then sharp" instead of "holes, then sharp". The underlay is only * shown while its main layer is loading, so a trimmed map's translucent * margin never stacks twice once the real tiles are in. */ const hasPreview = (m) => !m.base && m.maxNativeZoom > PERF.previewLevel + 1; const previewOptions = (m, paneName, version) => ({ ...tileOptions(m, paneName, false, version), maxNativeZoom: Math.max(0, Math.min(m.maxNativeZoom, PERF.previewLevel) - boost), keepBuffer: 4, updateWhenIdle: true, updateInterval: 500, zIndex: 0, className: 'tile-preview', }); const setLayerSource = (m, trimmed) => { const layer = layers.get(m.id); if (!layer) return; const nextKind = trimmed && usesPermanentTrim(m) ? 'trimmed' : 'original'; if (layer._tarkovSource === nextKind) return; layer._tarkovSource = nextKind; layer.options.version = nextKind === 'trimmed' ? m.trimmedVersion : m.version; layer.setUrl(tileUrl(m, nextKind === 'trimmed')); const preview = previewLayers.get(m.id); if (preview) { preview.options.version = layer.options.version; preview.setUrl(tileUrl(m, nextKind === 'trimmed')); } }; const ensureInsideLayer = (m) => { if (insideLayers.has(m.id)) return insideLayers.get(m.id); const paneName = `map-${m.id}-inside`; const pane = map.createPane(paneName); pane.style.zIndex = String(paneZ(m.id) + 1); pane.style.pointerEvents = 'none'; pane.style.display = 'none'; insidePanes.set(m.id, pane); const layer = new OffsetTileLayer( `tiles/${m.id}/{z}/{x}/{y}.webp`, tileOptions(m, paneName), ).addTo(map); insideLayers.set(m.id, layer); updatePreviewTransform(m); return layer; }; const updateTrimClip = (m, points) => { const pane = insidePanes.get(m.id); if (!pane || points.length < 3) return; const projected = points.map(([x, y]) => map.latLngToLayerPoint([ m.origin[1] + y * m.size[1], m.origin[0] + x * m.size[0], ])); pane.style.clipPath = `polygon(${projected.map((p) => `${p.x}px ${p.y}px`).join(',')})`; }; const renderTrim = (m, points, transparency) => { const outside = panes.get(m.id); if (!outside) return; // Editing uses the untouched source plus a live preview. The normal saved // view switches back to the separately rasterized trimmed tile pyramid. setLayerSource(m, false); if (points.length < 3) { outside.style.opacity = '1'; const inside = insidePanes.get(m.id); if (inside) inside.style.display = 'none'; return; } ensureInsideLayer(m); outside.style.opacity = String(1 - transparency); const inside = insidePanes.get(m.id); inside.style.display = ''; updateTrimClip(m, points); }; const restoreMapAppearance = (m) => { if (!m || m.base) return; panes.get(m.id).style.opacity = '1'; const inside = insidePanes.get(m.id); if (inside) inside.style.display = 'none'; setLayerSource(m, true); }; for (const m of world.maps) { // The base map is the backdrop: it is a handful of tiles, always loaded, // and Leaflet upscales it past its native level -- so a gap while detail // tiles load shows blurry terrain rather than the page background. const isBase = !!m.base; let paneName; if (!isBase) { paneName = `map-${m.id}`; const pane = map.createPane(paneName); pane.style.zIndex = String(paneZ(m.id)); pane.style.pointerEvents = 'none'; panes.set(m.id, pane); } const trimmed = usesPermanentTrim(m); const version = trimmed ? m.trimmedVersion : m.version; // The underlay goes first so its few tiny requests leave before the // main layer's burst. const preview = hasPreview(m) ? new OffsetTileLayer(tileUrl(m, trimmed), previewOptions(m, paneName, version)).addTo(map) : null; const layer = new OffsetTileLayer( tileUrl(m, trimmed), tileOptions(m, paneName, isBase, version), ).addTo(map); layer._tarkovSource = trimmed ? 'trimmed' : 'original'; layers.set(m.id, layer); if (preview) { previewLayers.set(m.id, preview); const setPreviewVisible = (visible) => { const container = preview.getContainer(); if (container) container.style.opacity = visible ? '1' : '0'; }; layer.on('loading', () => setPreviewVisible(true)); layer.on('load', () => setPreviewVisible(false)); } } // --- semantic PSD markers -------------------------------------------- const markerPane = map.createPane('semantic-markers'); markerPane.style.zIndex = '900'; // Hover detail boxes must cover neighbouring markers, not hide behind them. map.getPane('tooltipPane').style.zIndex = '940'; const markerLayer = L.layerGroup(); const escapeHTML = (value) => String(value ?? '').replace( /[&<>"']/g, (char) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[char]), ); const markerMaps = new Map(world.maps.map((m) => [m.id, m])); const markerDefaults = { color: '#5d6876', size: 18, symbol: '•', displayText: false, defaultVisible: true, visibleMinZoom: 2.5, labelMinZoom: 6, extractLabelMinZoom: 2, gridSize: 2048, viewportPadding: 0.15, ...(markerConfig.defaults ?? {}), }; const markerVisibleMinZoom = Number(markerDefaults.visibleMinZoom) || 2.5; const markerZoomVisible = () => map.getZoom() >= markerVisibleMinZoom; const extractCategories = new Set([ 'extract-pmc', 'extract-scav', 'extract-neutral', 'extract-hidden', 'transit', ]); const localizedMarkerLabel = (record, settings = categoryConfig(record.category)) => ( language === 'zh-CN' && extractCategories.has(record.category) ? extractTranslations[record.id] || record.label || settings.label : record.label || settings.label || record.category.replaceAll('-', ' ') ); const markerVisibilityVersion = Number(markerConfig.visibilityVersion) || 1; const categoryStorageKey = (category) => ( `tarkov-marker-v${markerVisibilityVersion}-category-${category}` ); // Memoised: this used to allocate a fresh merged object per marker per // layout pass, and safeColor() below runs CSS.supports on every call. const categoryConfigCache = new Map(); const categoryConfig = (category) => { let settings = categoryConfigCache.get(category); if (!settings) { settings = { ...markerDefaults, ...(markerConfig.categories?.[category] ?? {}) }; categoryConfigCache.set(category, settings); } return settings; }; const safeColor = (value) => ( typeof value === 'string' && CSS.supports('color', value) ? value : markerDefaults.color ); const safeSize = (value) => Math.max(8, Math.min(40, Number(value) || markerDefaults.size)); const gridSize = Math.max(256, Number(markerDefaults.gridSize) || 2048); const markerIndex = new Map(); const markerCounts = new Map(); const markerRecords = new Map(); const categoryCountNodes = new Map(); const markerEditing = { active: false, selectedMapId: null, dropping: false, }; let selectEditableMarker = () => {}; let saveDraggedMarker = () => {}; let onEditedMarkerDrag = () => {}; const localMarkerVersion = 1; const localMarkerEditKey = (mapId) => `tarkov-local-markers-v${localMarkerVersion}-${mapId}`; const publishedMarkerCacheKey = (mapId) => ( `tarkov-published-markers-v${localMarkerVersion}-${mapId}` ); const readStoredJSON = (key, fallback) => { try { const value = localStorage.getItem(key); return value ? JSON.parse(value) : fallback; } catch { return fallback; } }; const writeStoredJSON = (key, value, required = false) => { try { localStorage.setItem(key, JSON.stringify(value)); } catch (error) { if (required) throw new Error(`Browser storage failed: ${error.message}`); } }; const readLocalMarkerEdits = (mapId) => { const value = readStoredJSON(localMarkerEditKey(mapId), {}); return { overrides: value?.overrides && typeof value.overrides === 'object' ? value.overrides : {}, added: Array.isArray(value?.added) ? value.added : [], deleted: Array.isArray(value?.deleted) ? value.deleted : [], }; }; const writeLocalMarkerEdits = (mapId, edits) => { writeStoredJSON(localMarkerEditKey(mapId), { version: 1, ...edits }, true); }; const applyLocalMarkerEdits = (mapId, published) => { if (markerPersistence !== 'local') return published; const edits = readLocalMarkerEdits(mapId); const deleted = new Set(edits.deleted); const markers = published .filter((marker) => !deleted.has(marker.id)) .map((marker) => ({ ...marker, ...(edits.overrides[marker.id] ?? {}) })); const ids = new Set(markers.map((marker) => marker.id)); markers.push(...edits.added.filter((marker) => !ids.has(marker.id))); return markers; }; // World-space grid index: panning queries only intersecting cells rather // than scanning or instantiating all PSD records. const indexMarker = (marker) => { const m = markerMaps.get(marker.mapId); if (!m || !Number.isFinite(marker.x) || !Number.isFinite(marker.y)) return null; const category = String(marker.category || 'poi').replace(/[^a-z0-9-]/gi, ''); const record = { ...marker, category, worldX: m.origin[0] + marker.x * m.size[0], worldY: m.origin[1] + marker.y * m.size[1], mapName: m.name, }; markerRecords.set(record.id, record); if (!markerIndex.has(m.id)) markerIndex.set(m.id, new Map()); const cell = `${Math.floor(record.worldX / gridSize)},${Math.floor(record.worldY / gridSize)}`; const cells = markerIndex.get(m.id); if (!cells.has(cell)) cells.set(cell, []); cells.get(cell).push(record); markerCounts.set(category, (markerCounts.get(category) ?? 0) + 1); return record; }; const removeIndexedMarker = (id) => { const record = markerRecords.get(id); if (!record) return; const cell = `${Math.floor(record.worldX / gridSize)},${Math.floor(record.worldY / gridSize)}`; const cells = markerIndex.get(record.mapId); const records = cells?.get(cell); if (records) { const index = records.findIndex((item) => item.id === id); if (index >= 0) records.splice(index, 1); if (!records.length) cells.delete(cell); } markerRecords.delete(id); markerCounts.set(record.category, Math.max(0, (markerCounts.get(record.category) ?? 1) - 1)); const rendered = renderedMarkers?.get(id); if (rendered) { markerLayer.removeLayer(rendered); renderedMarkers.delete(id); } }; const loadedMarkerMaps = new Map(); const markerMapRequests = new Map(); let activeMarkerMapIds = new Set(); const fetchMarkerMap = (mapId, { force = false, publishedOnly = false } = {}) => { if (!force && !publishedOnly && markerMapRequests.has(mapId)) { return markerMapRequests.get(mapId); } const suffix = force ? `?refresh=${Date.now()}` : ''; const requestCache = force ? 'reload' : 'no-cache'; const request = Promise.all([ fetch(`data/markers/${encodeURIComponent(mapId)}.json${suffix}`, { cache: requestCache }) .then((response) => { if (response.status === 404) return { markers: [] }; if (!response.ok) throw new Error(`${mapId} markers: ${response.status}`); return response.json(); }), fetch(`data/marker-edits/${encodeURIComponent(mapId)}.json${suffix}`, { cache: requestCache }) .then((response) => { if (response.status === 404) return { overrides: {}, added: [] }; if (!response.ok) throw new Error(`${mapId} marker edits: ${response.status}`); return response.json(); }), ]).then(([raw, edits]) => { const overrides = edits.overrides ?? {}; const deleted = new Set(edits.deleted ?? []); const markers = (raw.markers ?? []) .filter((marker) => !deleted.has(marker.id)) .map((marker) => ({ ...marker, ...(overrides[marker.id] ?? {}), })); const ids = new Set(markers.map((marker) => marker.id)); markers.push(...(edits.added ?? []).filter((marker) => !ids.has(marker.id))); if (markerPersistence === 'local') { writeStoredJSON(publishedMarkerCacheKey(mapId), { markers }); } return publishedOnly ? markers : applyLocalMarkerEdits(mapId, markers); }).catch((error) => { if (force || markerPersistence !== 'local') throw error; const cached = readStoredJSON(publishedMarkerCacheKey(mapId), null); if (!Array.isArray(cached?.markers)) throw error; return publishedOnly ? cached.markers : applyLocalMarkerEdits(mapId, cached.markers); }).finally(() => { if (markerMapRequests.get(mapId) === request) markerMapRequests.delete(mapId); }); if (!force && !publishedOnly) markerMapRequests.set(mapId, request); return request; }; const categoryVisible = new Map(); const allCategories = new Set([ ...Object.keys(markerConfig.categories ?? {}), ...markerCounts.keys(), ]); for (const category of allCategories) { const stored = localStorage.getItem(categoryStorageKey(category)); categoryVisible.set(category, stored === null ? categoryConfig(category).defaultVisible !== false : stored !== 'false'); } const createMarkerIcon = (record) => { const settings = categoryConfig(record.category); const size = safeSize(settings.size); const color = safeColor(settings.color); const textColor = safeColor(settings.textColor || '#f5f7f8'); const label = localizedMarkerLabel(record, settings); const text = settings.displayText ? `${escapeHTML(label)}` : ''; return L.divIcon({ className: `poi-icon marker-${record.category}${extractCategories.has(record.category) ? ' marker-extract' : ''}`, iconSize: [size, size], iconAnchor: [size / 2, size / 2], html: `` + `` + `${escapeHTML(settings.symbol ?? '•')}${text}`, }); }; const markerTooltipHTML = (record) => { const settings = categoryConfig(record.category); return `${escapeHTML(localizedMarkerLabel(record, settings))}` + `${escapeHTML(settings.label ?? record.category)} · ${escapeHTML(record.mapName)}`; }; const createMarker = (record) => { const settings = categoryConfig(record.category); const size = safeSize(settings.size); const leafletMarker = L.marker([record.worldY, record.worldX], { icon: createMarkerIcon(record), pane: 'semantic-markers', interactive: true, keyboard: false, draggable: markerEditingEnabled, zIndexOffset: extractCategories.has(record.category) ? 5000 : 0, }); leafletMarker.bindTooltip( markerTooltipHTML(record), { direction: 'top', offset: [0, -(size * markerScale) / 2], className: 'poi-tooltip' }, ); leafletMarker.on('click', (event) => { if (!markerEditing.active) return; L.DomEvent.stopPropagation(event.originalEvent); selectEditableMarker(record.id); }); leafletMarker.on('dragstart', () => { if (!markerEditing.active) return; leafletMarker.closeTooltip(); selectEditableMarker(record.id, { pan: false }); }); leafletMarker.on('drag', () => { if (markerEditing.active) onEditedMarkerDrag(record.id, leafletMarker); }); leafletMarker.on('dragend', () => { if (markerEditing.active) saveDraggedMarker(record.id, leafletMarker); }); return leafletMarker; }; let focusedMarkerIds = []; let markerRefreshFrame = null; const renderedMarkers = new Map(); refreshLocalizedMarkers = () => { for (const [id, leafletMarker] of renderedMarkers) { const record = markerRecords.get(id); if (!record) continue; leafletMarker.setIcon(createMarkerIcon(record)); leafletMarker.setTooltipContent(markerTooltipHTML(record)); } scheduleMarkerLabelLayout(); }; let markerLabelLayoutFrame = null; // Marker/label size multiplier (the slider, top right). Applied as a CSS // transform on .poi-content, so changing it never rebuilds an icon; the // label layout below converts between visual and local space with it. const MARKER_SCALE_KEY = 'tarkov-marker-scale'; const MARKER_SCALE_MIN = 0.5; const MARKER_SCALE_MAX = 2; let markerScale = Math.min(MARKER_SCALE_MAX, Math.max(MARKER_SCALE_MIN, Number(localStorage.getItem(MARKER_SCALE_KEY)) || 1)); // Resolve and keep the parts of a rendered marker the layout needs, once, // instead of two querySelector calls per marker per layout pass. const cacheMarkerParts = (leafletMarker, record) => { const element = leafletMarker.getElement(); if (!element) return; leafletMarker._poi = { size: safeSize(categoryConfig(record.category).size), extract: extractCategories.has(record.category), label: element.querySelector('.poi-label'), leader: element.querySelector('.poi-leader'), }; }; const labelCollisionCellSize = 128; const rectCells = (rect) => { const keys = []; const x0 = Math.floor(rect.left / labelCollisionCellSize); const x1 = Math.floor(rect.right / labelCollisionCellSize); const y0 = Math.floor(rect.top / labelCollisionCellSize); const y1 = Math.floor(rect.bottom / labelCollisionCellSize); for (let y = y0; y <= y1; y += 1) { for (let x = x0; x <= x1; x += 1) keys.push(`${x},${y}`); } return keys; }; const paddedRect = (left, top, width, height, padding = 3) => ({ left: left - padding, top: top - padding, right: left + width + padding, bottom: top + height + padding, }); const rectsOverlap = (a, b) => ( a.left < b.right && a.right > b.left && a.top < b.bottom && a.bottom > b.top ); // Grid-indexed rectangle set: a collision test touches only the cells the // candidate overlaps. Used for labels/panels and -- new -- for icons, which // used to be a linear scan of every icon for every candidate of every label. const makeRectIndex = () => { const cells = new Map(); return { add(rect) { for (const key of rectCells(rect)) { let list = cells.get(key); if (!list) { list = []; cells.set(key, list); } list.push(rect); } }, hits(rect) { for (const key of rectCells(rect)) { const list = cells.get(key); if (!list) continue; for (const existing of list) if (rectsOverlap(rect, existing)) return true; } return false; }, }; }; const labelAngles = [ 0, Math.PI, -Math.PI / 2, Math.PI / 2, -Math.PI / 4, Math.PI / 4, -3 * Math.PI / 4, 3 * Math.PI / 4, -Math.PI / 8, Math.PI / 8, -3 * Math.PI / 8, 3 * Math.PI / 8, -5 * Math.PI / 8, 5 * Math.PI / 8, -7 * Math.PI / 8, 7 * Math.PI / 8, ].map((angle) => [Math.cos(angle), Math.sin(angle)]); const layoutMarkerLabels = () => { const container = map.getContainer(); const viewportWidth = container.clientWidth; const viewportHeight = container.clientHeight; if (!viewportWidth || !viewportHeight) return; // Mirrors style.css: below the label zooms every label is display:none. const labelsVisible = container.classList.contains('marker-labels-visible'); const extractLabelsVisible = container.classList.contains('marker-extract-labels-visible'); if (!labelsVisible && !extractLabelsVisible) return; const started = performance.now(); const scale = markerScale; const occupied = makeRectIndex(); const containerBounds = container.getBoundingClientRect(); for (const id of ['panel', 'marker-scale-control']) { const element = document.getElementById(id); if (!element) continue; const bounds = element.getBoundingClientRect(); occupied.add(paddedRect( bounds.left - containerBounds.left, bounds.top - containerBounds.top, bounds.width, bounds.height, 6, )); } // Pass 1, writes only: reset every label and leader to its natural spot, // and index every icon. Pass 2, reads only. Interleaving the two forces // one layout per label; separated, the browser does a single layout. const icons = makeRectIndex(); const reset = []; for (const [id, leafletMarker] of renderedMarkers) { const poi = leafletMarker._poi; const record = markerRecords.get(id); if (!poi || !record) continue; const point = map.latLngToContainerPoint(leafletMarker.getLatLng()); const visual = poi.size * scale; icons.add(paddedRect(point.x - visual / 2, point.y - visual / 2, visual, visual, 2)); if (!poi.label || !(labelsVisible || (extractLabelsVisible && poi.extract))) continue; // Markers kept just off-screen (pan hysteresis) need no label. if (point.x < -viewportWidth / 2 || point.y < -viewportHeight / 2 || point.x > viewportWidth * 1.5 || point.y > viewportHeight * 1.5) { poi.label.classList.add('poi-label-hidden'); continue; } poi.label.classList.remove('poi-label-hidden'); for (const property of ['left', 'top', 'transform']) poi.label.style.removeProperty(property); for (const property of ['display', 'left', 'top', 'width', 'transform']) { poi.leader.style.removeProperty(property); } reset.push({ id, poi, record, point }); } const items = []; for (const entry of reset) { const bounds = entry.poi.label.getBoundingClientRect(); // visual, i.e. scaled if (entry.record.category === 'location') { occupied.add(paddedRect( bounds.left - containerBounds.left, bounds.top - containerBounds.top, bounds.width, bounds.height, )); continue; } items.push({ ...entry, size: entry.poi.size * scale, width: Math.ceil(bounds.width), height: Math.ceil(bounds.height), }); } items.sort((a, b) => ( Number(!extractCategories.has(a.record.category)) - Number(!extractCategories.has(b.record.category)) || a.point.y - b.point.y || a.point.x - b.point.x || a.id.localeCompare(b.id) )); // Prefer not to obscure marker icons, but do not let a dense icon field // push a label across the viewport. Label/panel collisions remain hard // constraints; icon collisions are only a placement preference. // Candidates are generated ring by ring and the search stops at the // first good one, instead of materialising all 128 per label up front. const padding = 8; for (const item of items) { const { point, width, height, size, poi } = item; const { label, leader } = poi; const radius = size / 2; let chosen = null; let iconOverlapFallback = null; search: for (let ring = 0; ring < 8; ring += 1) { const clearance = radius + 8 + ring * 14; for (const [dx, dy] of labelAngles) { const distance = clearance + Math.abs(dx) * width / 2 + Math.abs(dy) * height / 2; const left = point.x + dx * distance - width / 2; const top = point.y + dy * distance - height / 2; if (left < padding || top < padding || left + width > viewportWidth - padding || top + height > viewportHeight - padding) continue; const rect = paddedRect(left, top, width, height); if (occupied.hits(rect)) continue; const candidate = { left, top, rect, displaced: ring > 0 }; if (!iconOverlapFallback) iconOverlapFallback = candidate; if (icons.hits(rect)) continue; chosen = candidate; break search; } } chosen ??= iconOverlapFallback; if (!chosen) { label.classList.add('poi-label-hidden'); continue; } occupied.add(chosen.rect); // Styles live in the icon's local (unscaled) space; the size slider // scales .poi-content about its centre, so local = half + (visual - centre) / scale. const half = poi.size / 2; label.style.left = `${half + (chosen.left - point.x) / scale}px`; label.style.top = `${half + (chosen.top - point.y) / scale}px`; label.style.transform = 'none'; const targetX = Math.max(chosen.left, Math.min(point.x, chosen.left + width)); const targetY = Math.max(chosen.top, Math.min(point.y, chosen.top + height)); const dx = targetX - point.x; const dy = targetY - point.y; const distance = Math.hypot(dx, dy); const startDistance = radius + 3; const lineLength = Math.max(0, distance - startDistance); if (chosen.displaced && lineLength > 4) { const ux = dx / distance; const uy = dy / distance; leader.style.display = 'block'; leader.style.left = `${half + (ux * startDistance) / scale}px`; leader.style.top = `${half + (uy * startDistance) / scale}px`; leader.style.width = `${lineLength / scale}px`; leader.style.transform = `rotate(${Math.atan2(dy, dx)}rad)`; } } // Visible in DevTools > Performance and performance.getEntriesByName(). try { performance.measure('tarkov:marker-labels', { start: started, end: performance.now() }); } catch { /* old browser */ } }; const scheduleMarkerLabelLayout = () => { if (markerLabelLayoutFrame !== null) return; markerLabelLayoutFrame = requestAnimationFrame(() => { markerLabelLayoutFrame = null; layoutMarkerLabels(); }); }; const refreshMarkerCounts = () => { for (const [category, node] of categoryCountNodes) { const settings = categoryConfig(category); node.textContent = `${settings.label ?? category} (${markerCounts.get(category) ?? 0})`; } const button = document.getElementById('toggle-markers'); if (button) button.textContent = `Markers (${markerRecords.size})`; }; const replaceMarkerRecord = (record) => { removeIndexedMarker(record.id); const indexed = indexMarker(record); if (!loadedMarkerMaps.has(record.mapId)) loadedMarkerMaps.set(record.mapId, new Set()); loadedMarkerMaps.get(record.mapId).add(record.id); refreshMarkerCounts(); scheduleMarkerRefresh(); return indexed; }; const replaceLoadedMarkerMap = (mapId, markers) => { for (const markerId of loadedMarkerMaps.get(mapId) ?? []) removeIndexedMarker(markerId); const markerIds = new Set(); for (const marker of markers) { const indexed = indexMarker(marker); if (indexed) markerIds.add(indexed.id); } loadedMarkerMaps.set(mapId, markerIds); refreshMarkerCounts(); scheduleMarkerRefresh(); }; let markersVisible = localStorage.getItem('tarkov-markers-visible') !== 'false'; const refreshMarkers = () => { markerRefreshFrame = null; try { if (!markersVisible || !markerZoomVisible()) return; const viewportPadding = Number(markerDefaults.viewportPadding) || 0.15; const bounds = map.getBounds().pad(viewportPadding); // Markers that drift just outside the padded view are kept a while // longer, so a short pan back and forth does not destroy and recreate // their DOM. const keepBounds = map.getBounds().pad(viewportPadding * 3); const x0 = Math.floor(bounds.getWest() / gridSize); const x1 = Math.floor(bounds.getEast() / gridSize); const y0 = Math.floor(bounds.getSouth() / gridSize); const y1 = Math.floor(bounds.getNorth() / gridSize); const mapIds = focusedMarkerIds.length ? focusedMarkerIds : [...markerIndex.keys()]; const desired = new Map(); for (const mapId of mapIds) { const cells = markerIndex.get(mapId); if (!cells) continue; for (let gy = y0; gy <= y1; gy += 1) { for (let gx = x0; gx <= x1; gx += 1) { for (const record of cells.get(`${gx},${gy}`) ?? []) { if (categoryVisible.get(record.category) === false) continue; if (bounds.contains([record.worldY, record.worldX])) desired.set(record.id, record); } } } } for (const [id, leafletMarker] of renderedMarkers) { if (desired.has(id)) continue; const record = markerRecords.get(id); if (record && categoryVisible.get(record.category) !== false && mapIds.includes(record.mapId) && keepBounds.contains([record.worldY, record.worldX])) continue; markerLayer.removeLayer(leafletMarker); renderedMarkers.delete(id); } for (const [id, record] of desired) { if (renderedMarkers.has(id)) continue; const leafletMarker = createMarker(record); renderedMarkers.set(id, leafletMarker); markerLayer.addLayer(leafletMarker); cacheMarkerParts(leafletMarker, record); if (!markerEditing.active) leafletMarker.dragging?.disable(); } scheduleMarkerLabelLayout(); } catch (error) { document.getElementById('toggle-markers').title = `Marker rendering failed: ${error.message}`; throw error; } }; const scheduleMarkerRefresh = () => { if (markerRefreshFrame !== null) return; markerRefreshFrame = requestAnimationFrame(refreshMarkers); }; updateMarkerFocus = (mapIds) => { focusedMarkerIds = mapIds; activeMarkerMapIds = new Set(mapIds); for (const [mapId, markerIds] of loadedMarkerMaps) { if (activeMarkerMapIds.has(mapId)) continue; for (const markerId of markerIds) removeIndexedMarker(markerId); loadedMarkerMaps.delete(mapId); } refreshMarkerCounts(); scheduleMarkerRefresh(); const missing = mapIds.filter((mapId) => !loadedMarkerMaps.has(mapId)); Promise.all(missing.map(async (mapId) => ({ mapId, markers: await fetchMarkerMap(mapId) }))) .then((results) => { for (const { mapId, markers } of results) { if (!activeMarkerMapIds.has(mapId) || loadedMarkerMaps.has(mapId)) continue; const markerIds = new Set(); for (const marker of markers) { const indexed = indexMarker(marker); if (indexed) markerIds.add(indexed.id); } loadedMarkerMaps.set(mapId, markerIds); } refreshMarkerCounts(); scheduleMarkerRefresh(); }) .catch((error) => { markerButton.title = `Marker loading failed: ${error.message}`; console.error(error); }); }; const markerButton = document.getElementById('toggle-markers'); const renderMarkerVisibility = () => { const shouldRender = markersVisible && markerZoomVisible(); if (shouldRender && !map.hasLayer(markerLayer)) markerLayer.addTo(map); if (!shouldRender && map.hasLayer(markerLayer)) { map.removeLayer(markerLayer); renderedMarkers.clear(); markerLayer.clearLayers(); } markerButton.setAttribute('aria-pressed', String(markersVisible)); // Called on every zoomend; only touch the DOM when something changed. const text = `Markers (${markerRecords.size})`; if (markerButton.textContent !== text) markerButton.textContent = text; const title = markersVisible && !shouldRender ? `Markers appear at zoom ${markerVisibleMinZoom} and closer.` : ''; if (markerButton.title !== title) markerButton.title = title; if (shouldRender) scheduleMarkerRefresh(); }; markerButton.addEventListener('click', () => { markersVisible = !markersVisible; localStorage.setItem('tarkov-markers-visible', String(markersVisible)); renderMarkerVisibility(); }); renderMarkerVisibility(); const categoryContainer = document.getElementById('marker-categories'); const groups = markerConfig.groups?.length ? markerConfig.groups : [{ id: 'markers', label: 'Markers' }]; for (const group of groups) { const categories = [...allCategories].filter((category) => ( (categoryConfig(category).group ?? 'markers') === group.id )); if (!categories.length) continue; const fieldset = document.createElement('fieldset'); const legend = document.createElement('legend'); legend.textContent = group.label; fieldset.appendChild(legend); for (const category of categories) { const settings = categoryConfig(category); const label = document.createElement('label'); const checkbox = document.createElement('input'); checkbox.type = 'checkbox'; checkbox.dataset.category = category; checkbox.checked = categoryVisible.get(category) !== false; checkbox.addEventListener('change', () => { categoryVisible.set(category, checkbox.checked); localStorage.setItem(categoryStorageKey(category), String(checkbox.checked)); scheduleMarkerRefresh(); }); const swatch = document.createElement('span'); swatch.className = 'marker-category-swatch'; swatch.style.background = safeColor(settings.color); swatch.textContent = settings.symbol ?? '•'; const text = document.createElement('span'); text.textContent = `${settings.label ?? category} (${markerCounts.get(category) ?? 0})`; categoryCountNodes.set(category, text); label.append(checkbox, swatch, text); fieldset.appendChild(label); } categoryContainer.appendChild(fieldset); } const updateMarkerDensity = () => { map.getContainer().classList.toggle( 'marker-labels-visible', map.getZoom() >= (Number(markerDefaults.labelMinZoom) || 6), ); map.getContainer().classList.toggle( 'marker-extract-labels-visible', map.getZoom() >= (Number(markerDefaults.extractLabelMinZoom) || 2), ); map.getContainer().classList.toggle('marker-overview', map.getZoom() < 2.5); renderMarkerVisibility(); }; // zoomend, not zoom: during the zoom animation the marker pane is simply // transformed, so re-culling and re-laying-out labels every frame only // costs forced layouts. map.on('zoomend', updateMarkerDensity); map.on('moveend zoomend resize', scheduleMarkerRefresh); document.getElementById('panel')?.addEventListener('toggle', scheduleMarkerLabelLayout); document.getElementById('marker-settings')?.addEventListener('toggle', scheduleMarkerLabelLayout); if ('ResizeObserver' in window) { const markerPanelObserver = new ResizeObserver(scheduleMarkerLabelLayout); markerPanelObserver.observe(document.getElementById('panel')); } updateMarkerDensity(); // --- marker size slider ------------------------------------------------ // Logarithmic so 1x sits exactly mid-track: 0.5x ... 1x ... 2x. const markerScaleInput = document.getElementById('marker-scale'); const markerScaleValue = document.getElementById('marker-scale-value'); const applyMarkerScale = (value, persist = true) => { markerScale = Math.min(MARKER_SCALE_MAX, Math.max(MARKER_SCALE_MIN, value)); map.getContainer().style.setProperty('--marker-scale', String(markerScale)); markerScaleInput.value = String(Math.log10(markerScale)); markerScaleValue.textContent = `${markerScale.toFixed(markerScale < 1 ? 2 : 1)}×`; for (const leafletMarker of renderedMarkers.values()) { const tooltip = leafletMarker.getTooltip(); const poi = leafletMarker._poi; if (tooltip && poi) tooltip.options.offset = L.point(0, -(poi.size * markerScale) / 2); } if (persist) localStorage.setItem(MARKER_SCALE_KEY, String(markerScale)); scheduleMarkerLabelLayout(); }; markerScaleInput.min = String(Math.log10(MARKER_SCALE_MIN)); markerScaleInput.max = String(Math.log10(MARKER_SCALE_MAX)); markerScaleInput.addEventListener('input', () => applyMarkerScale(10 ** Number(markerScaleInput.value))); markerScaleValue.addEventListener('click', () => applyMarkerScale(1)); applyMarkerScale(markerScale, false); // --- picker ----------------------------------------------------------- // The Maps panel expands on hover; clicking its header pins it open. While // unpinned it collapses 2 s after the pointer (or keyboard focus) leaves. const panel = document.getElementById('panel'); const panelSummary = panel.querySelector('summary'); const panelPin = document.getElementById('panel-pin'); const PANEL_PIN_KEY = 'tarkov-panel-pinned'; const hoverCapable = window.matchMedia('(hover: hover)'); let panelPinned = localStorage.getItem(PANEL_PIN_KEY) === 'true'; let panelHovered = false; let panelCollapseTimer = null; const cancelPanelCollapse = () => { if (panelCollapseTimer === null) return; clearTimeout(panelCollapseTimer); panelCollapseTimer = null; }; const schedulePanelCollapse = (delay = 2000) => { cancelPanelCollapse(); if (panelPinned) return; panelCollapseTimer = setTimeout(() => { panelCollapseTimer = null; if (!panelPinned && !panelHovered) panel.open = false; }, delay); }; const renderPanelPin = () => { panel.dataset.pinned = String(panelPinned); panelPin.textContent = panelPinned ? 'pinned' : 'unpinned'; panelSummary.title = panelPinned ? 'Pinned open. Click to unpin; it then collapses 2 s after the pointer leaves.' : 'Hover to expand. Click to pin it open.'; }; const setPanelPinned = (pinned) => { panelPinned = pinned; localStorage.setItem(PANEL_PIN_KEY, String(pinned)); renderPanelPin(); if (pinned) { cancelPanelCollapse(); panel.open = true; } else if (!hoverCapable.matches) { panel.open = false; // no hover to keep it alive: unpin means close } else { schedulePanelCollapse(); } }; panelSummary.addEventListener('click', (event) => { event.preventDefault(); // the header is the pin toggle, not the open toggle setPanelPinned(!panelPinned); }); panel.addEventListener('mouseenter', () => { panelHovered = true; cancelPanelCollapse(); panel.open = true; }); panel.addEventListener('mouseleave', () => { panelHovered = false; schedulePanelCollapse(); }); panel.addEventListener('focusin', () => { cancelPanelCollapse(); panel.open = true; }); panel.addEventListener('focusout', (event) => { if (!panel.contains(event.relatedTarget)) schedulePanelCollapse(); }); panel.open = panelPinned; renderPanelPin(); const list = document.getElementById('maplist'); const overviewButton = document.getElementById('overview-map'); const editButton = document.getElementById('edit-placement'); const trimButton = document.getElementById('edit-trim'); const editorActions = editButton.closest('.editor-mode-actions'); const exportButton = document.getElementById('export-static'); const exportStatus = document.getElementById('export-status'); editButton.hidden = !mapEditingEnabled; trimButton.hidden = !mapEditingEnabled; exportButton.hidden = !exportingEnabled; document.getElementById('edit-markers').hidden = !markerEditingEnabled; if (editorActions) { editorActions.hidden = !(mapEditingEnabled || markerEditingEnabled || exportingEnabled); editorActions.dataset.markerOnly = String( markerEditingEnabled && !mapEditingEnabled && !exportingEnabled, ); } const editorPanel = document.getElementById('placement-editor'); const editorName = document.getElementById('placement-name'); const xInput = document.getElementById('placement-x'); const yInput = document.getElementById('placement-y'); const widthInput = document.getElementById('placement-width'); const heightInput = document.getElementById('placement-height'); const aspectOutput = document.getElementById('placement-aspect'); const resetButton = document.getElementById('placement-reset'); const saveButton = document.getElementById('placement-save'); const status = document.getElementById('placement-status'); const trimPanel = document.getElementById('trim-editor'); const trimName = document.getElementById('trim-name'); const trimTransparency = document.getElementById('trim-transparency'); const trimTransparencyValue = document.getElementById('trim-transparency-value'); const trimPointCount = document.getElementById('trim-point-count'); const trimUndo = document.getElementById('trim-undo'); const trimClear = document.getElementById('trim-clear'); const trimSave = document.getElementById('trim-save'); const trimStatus = document.getElementById('trim-status'); const markerEditButton = document.getElementById('edit-markers'); const markerEditorPanel = document.getElementById('marker-editor'); const markerEditorName = document.getElementById('marker-editor-name'); const markerDropButton = document.getElementById('marker-drop'); const markerResetButton = document.getElementById('marker-reset'); const markerEditStatus = document.getElementById('marker-edit-status'); const markerContextMenu = document.getElementById('marker-context-menu'); markerResetButton.hidden = markerPersistence !== 'local'; const byId = new Map(world.maps.map((m) => [m.id, m])); const editor = { selectedId: null, active: false, marker: null, outline: null, }; const trimEditor = { selectedId: null, active: false, points: [], transparency: 0.75, markers: [], outline: null, }; const editorCategories = [...allCategories].sort((a, b) => { const groupOrder = new Map(groups.map((group, index) => [group.id, index])); const aSettings = categoryConfig(a); const bSettings = categoryConfig(b); return (groupOrder.get(aSettings.group) ?? 999) - (groupOrder.get(bSettings.group) ?? 999) || String(aSettings.label ?? a).localeCompare(String(bSettings.label ?? b)); }); const categoryLabel = (category) => String(categoryConfig(category).label ?? category); const showMarkerStatus = (message, isError = false) => { markerEditStatus.textContent = message; markerEditStatus.dataset.error = String(isError); }; const setMarkerDropping = (dropping) => { markerEditing.dropping = dropping; markerDropButton.setAttribute('aria-pressed', String(dropping)); markerDropButton.textContent = dropping ? 'Cancel drop' : 'Drop new marker'; map.getContainer().classList.toggle('marker-dropping', dropping); }; // --- inline marker editor ---------------------------------------------- // Editing happens in a box anchored next to the marker (a Leaflet popup in // its own pane above the markers), not in the side panel. One "session" // object per open box: Enter or a left click anywhere else commits it, // Escape cancels it. Sessions are captured by value in the async commit so // a slow save cannot close a box that was opened for a different marker. map.createPane('marker-editor').style.zIndex = '950'; const inlineBox = document.createElement('div'); inlineBox.className = 'marker-edit-box'; inlineBox.innerHTML = ` Name Category Enter or click elsewhere saves · Esc cancels`; const inlineLabelInput = inlineBox.querySelector('.marker-edit-label'); const inlineCategoryInput = inlineBox.querySelector('.marker-edit-category'); const inlineMapName = inlineBox.querySelector('.marker-edit-box-map'); const inlineDeleteButton = inlineBox.querySelector('.marker-edit-box-delete'); for (const category of editorCategories) { const option = document.createElement('option'); option.value = category; option.textContent = categoryLabel(category); inlineCategoryInput.appendChild(option); } const inlinePopup = L.popup({ pane: 'marker-editor', className: 'marker-edit-popup', closeButton: false, closeOnClick: false, closeOnEscapeKey: false, autoClose: false, autoPan: true, autoPanPadding: [24, 24], minWidth: 230, maxWidth: 280, }).setContent(inlineBox); let editSession = null; const editedRecord = (session) => ( session.isNew ? session.draft : markerRecords.get(session.id) ); const editedLeafletMarker = (session) => ( session.isNew ? session.draftMarker : renderedMarkers.get(session.id) ); const discardDraft = (session) => { if (session?.draftMarker) map.removeLayer(session.draftMarker); }; const endSession = (session) => { if (!session || editSession !== session) return; editSession = null; if (inlinePopup.isOpen()) map.closePopup(inlinePopup); }; // Follow a dragging marker without auto-panning the map out from under // the pointer. const syncInlinePopup = (session, latlng) => { if (editSession !== session || !inlinePopup.isOpen()) return; inlinePopup.options.autoPan = false; inlinePopup.setLatLng(latlng); inlinePopup.options.autoPan = true; }; const restyleEditedMarker = (session, category) => { const record = editedRecord(session); const leafletMarker = editedLeafletMarker(session); if (!record || !leafletMarker) return; const styled = { ...record, category }; leafletMarker.setIcon(createMarkerIcon(styled)); if (session.isNew) { session.draft.category = category; } else { cacheMarkerParts(leafletMarker, styled); scheduleMarkerLabelLayout(); } }; const openSession = (session, { pan = true } = {}) => { if (editSession && editSession !== session) void commitInlineEditor(); editSession = session; const record = editedRecord(session); session.originalCategory = record.category; inlineLabelInput.value = record.label ?? ''; inlineCategoryInput.value = editorCategories.includes(record.category) ? record.category : (editorCategories[0] ?? 'poi'); inlineMapName.textContent = session.isNew ? `New marker · ${record.mapName}` : record.mapName; inlineDeleteButton.hidden = session.isNew; inlineDeleteButton.disabled = false; const size = safeSize(categoryConfig(record.category).size); inlinePopup.options.offset = L.point(0, -((size * markerScale) / 2) - 2); inlinePopup.options.autoPan = pan; const latlng = session.isNew ? session.draftMarker.getLatLng() : L.latLng(record.worldY, record.worldX); if (inlinePopup.isOpen()) { inlinePopup.setLatLng(latlng); inlinePopup.update(); } else { inlinePopup.setLatLng(latlng).openOn(map); } inlinePopup.options.autoPan = true; inlineLabelInput.focus({ preventScroll: true }); inlineLabelInput.select(); }; async function commitInlineEditor() { const session = editSession; if (!session || session.busy) return; const current = editedRecord(session); if (!current) { endSession(session); return; } const category = inlineCategoryInput.value; const typed = inlineLabelInput.value.trim(); const previousLabel = String(current.label ?? ''); const label = typed || (session.isNew ? categoryLabel(category) : previousLabel); if (!session.isNew && label === previousLabel && category === current.category) { endSession(session); return; } session.busy = true; showMarkerStatus(markerPersistence === 'local' ? 'Saving marker in this browser…' : 'Saving marker…'); try { const saved = await persistMarker({ ...current, label, category }); discardDraft(session); replaceMarkerRecord(saved); endSession(session); showMarkerStatus(markerPersistence === 'local' ? 'Marker saved locally.' : 'Marker saved.'); } catch (error) { session.busy = false; showMarkerStatus(`Save failed: ${error.message}`, true); if (editSession === session) inlineLabelInput.focus(); else discardDraft(session); } } const cancelInlineEditor = () => { const session = editSession; if (!session || session.busy) return; if (session.isNew) discardDraft(session); else if (inlineCategoryInput.value !== session.originalCategory) { restyleEditedMarker(session, session.originalCategory); } endSession(session); showMarkerStatus(session.isNew ? 'New marker discarded.' : 'Edit cancelled.'); }; // Leaving marker editing (mode toggle, map switch, reset) keeps whatever // was typed: "anything else saves". const clearMarkerSelection = () => { const session = editSession; if (session) { void commitInlineEditor(); endSession(session); } setMarkerDropping(false); }; const localMarkerValues = (record, id = record.id) => ({ id, mapId: record.mapId, x: Number(record.x), y: Number(record.y), label: String(record.label).trim(), category: String(record.category), source: id.startsWith('local-') ? 'Local marker' : record.source, }); const persistLocalMarker = (record) => { const edits = readLocalMarkerEdits(record.mapId); let id = record.id; if (!id || id.startsWith('draft-')) { const random = globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(16).slice(2)}`; id = `local-${random}`; } const saved = localMarkerValues(record, id); const addedIndex = edits.added.findIndex((marker) => marker.id === id); if (id.startsWith('local-') || addedIndex >= 0) { if (addedIndex >= 0) edits.added[addedIndex] = saved; else edits.added.push(saved); } else { edits.overrides[id] = { x: saved.x, y: saved.y, label: saved.label, category: saved.category, }; } edits.deleted = edits.deleted.filter((deletedId) => deletedId !== id); writeLocalMarkerEdits(record.mapId, edits); return { ...record, ...saved }; }; const deleteLocalMarker = (record) => { const edits = readLocalMarkerEdits(record.mapId); const addedLength = edits.added.length; edits.added = edits.added.filter((marker) => marker.id !== record.id); if (edits.added.length === addedLength) { if (!edits.deleted.includes(record.id)) edits.deleted.push(record.id); delete edits.overrides[record.id]; } writeLocalMarkerEdits(record.mapId, edits); }; const persistMarker = async (record) => { if (markerPersistence === 'local') return persistLocalMarker(record); const response = await fetch('api/marker', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: record.id?.startsWith('draft-') ? null : record.id, mapId: record.mapId, x: record.x, y: record.y, label: record.label, category: record.category, }), }); const responseText = await response.text(); let result; try { result = JSON.parse(responseText); } catch { result = {}; } if (!response.ok) throw new Error( result.error || 'This server is read-only; start it with server/run.ps1 -Editable', ); return result.marker; }; selectEditableMarker = (id, { pan = true } = {}) => { if (!markerEditing.active) return; const record = markerRecords.get(id); if (!record) return; if (editSession && !editSession.isNew && editSession.id === id) return; setMarkerDropping(false); renderedMarkers.get(id)?.closeTooltip(); openSession({ id, isNew: false, busy: false }, { pan }); showMarkerStatus('Rename it, choose a category, or drag it to move it.'); }; onEditedMarkerDrag = (id, leafletMarker) => { const session = editSession; if (session && !session.isNew && session.id === id) { syncInlinePopup(session, leafletMarker.getLatLng()); } }; saveDraggedMarker = async (id, leafletMarker) => { const record = markerRecords.get(id); const m = record && byId.get(record.mapId); const point = m && normalizedPoint(m, leafletMarker.getLatLng()); if (!record || !m || !point) { if (record) { leafletMarker.setLatLng([record.worldY, record.worldX]); onEditedMarkerDrag(id, leafletMarker); } showMarkerStatus('Keep the marker inside its source map.', true); return; } // A drag is a save: it takes whatever is in the edit box along with it. const session = editSession && !editSession.isNew && editSession.id === id ? editSession : null; const label = session ? (inlineLabelInput.value.trim() || record.label) : record.label; const category = session ? inlineCategoryInput.value : record.category; if (session) session.busy = true; leafletMarker.dragging.disable(); showMarkerStatus(markerPersistence === 'local' ? 'Saving the new marker position in this browser…' : 'Saving the new marker position…'); try { const saved = await persistMarker({ ...record, x: point[0], y: point[1], label, category }); replaceMarkerRecord(saved); if (session) endSession(session); selectEditableMarker(saved.id); showMarkerStatus(markerPersistence === 'local' ? 'Marker position saved locally.' : 'Marker position saved.'); } catch (error) { leafletMarker.setLatLng([record.worldY, record.worldX]); leafletMarker.dragging.enable(); onEditedMarkerDrag(id, leafletMarker); if (session) session.busy = false; showMarkerStatus(`Save failed: ${error.message}`, true); } }; function closeMarkerEditor() { clearMarkerSelection(); hideContextMenu(); markerEditing.active = false; markerEditorPanel.hidden = true; markerEditButton.setAttribute('aria-pressed', 'false'); map.getContainer().classList.remove('marker-editing', 'marker-dropping'); for (const leafletMarker of renderedMarkers.values()) leafletMarker.dragging?.disable(); showMarkerStatus(''); } function openMarkerEditor(m) { if (!markerEditingEnabled || !m || m.base) return; if (editor.active) closeEditor(); if (trimEditor.active) closeTrimEditor(); markerEditing.selectedMapId = m.id; markerEditing.active = true; markerEditorPanel.hidden = false; markerEditButton.disabled = false; markerEditButton.setAttribute('aria-pressed', 'true'); markerEditorName.textContent = `${m.name} markers`; if (!markersVisible) { markersVisible = true; localStorage.setItem('tarkov-markers-visible', 'true'); renderMarkerVisibility(); } map.getContainer().classList.add('marker-editing'); scheduleMarkerRefresh(); requestAnimationFrame(() => { for (const leafletMarker of renderedMarkers.values()) leafletMarker.dragging?.enable(); }); showMarkerStatus(markerPersistence === 'local' ? 'Changes are saved only in this browser. Right-click the map to add a marker.' : 'Right-click the map to add a marker, or click one to edit it.'); focus(m.id); } markerDropButton.addEventListener('click', () => { if (markerEditing.dropping) { setMarkerDropping(false); showMarkerStatus('Drop cancelled.'); return; } clearMarkerSelection(); setMarkerDropping(true); showMarkerStatus('Click inside the selected map to place a new marker (or right-click anywhere).'); }); markerResetButton.addEventListener('click', async () => { const mapId = markerEditing.selectedMapId; const m = byId.get(mapId); if (markerPersistence !== 'local' || !m) return; if (!window.confirm(`Discard all local marker changes for ${m.name} and reload the published markers?`)) { return; } markerResetButton.disabled = true; showMarkerStatus('Fetching the latest published markers…'); try { const published = await fetchMarkerMap(mapId, { force: true, publishedOnly: true }); localStorage.removeItem(localMarkerEditKey(mapId)); clearMarkerSelection(); replaceLoadedMarkerMap(mapId, published); showMarkerStatus('Local changes cleared. Latest published markers loaded.'); } catch (error) { showMarkerStatus(`Reset failed: ${error.message}`, true); } finally { markerResetButton.disabled = false; } }); inlineDeleteButton.addEventListener('click', async () => { const session = editSession; if (!session || session.isNew || session.busy) return; const record = markerRecords.get(session.id); if (!record) return; const confirmation = markerPersistence === 'local' ? `Delete “${record.label}” from this browser?` : `Delete “${record.label}”? The default backup is unchanged.`; if (!window.confirm(confirmation)) return; session.busy = true; inlineDeleteButton.disabled = true; showMarkerStatus('Deleting marker…'); try { if (markerPersistence === 'local') { deleteLocalMarker(record); } else { const response = await fetch('api/marker', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'delete', id: record.id, mapId: record.mapId }), }); const responseText = await response.text(); let result; try { result = JSON.parse(responseText); } catch { result = {}; } if (!response.ok) throw new Error( result.error || 'This server is read-only; start it with server/run.ps1 -Editable', ); } removeIndexedMarker(record.id); loadedMarkerMaps.get(record.mapId)?.delete(record.id); refreshMarkerCounts(); scheduleMarkerRefresh(); endSession(session); showMarkerStatus(markerPersistence === 'local' ? 'Marker deleted locally. Reset this map to restore published markers.' : 'Marker deleted. The read-only default remains available for restoration.'); } catch (error) { session.busy = false; inlineDeleteButton.disabled = false; showMarkerStatus(`Delete failed: ${error.message}`, true); } }); inlineCategoryInput.addEventListener('change', () => { if (editSession) restyleEditedMarker(editSession, inlineCategoryInput.value); }); inlineBox.addEventListener('keydown', (event) => { if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); cancelInlineEditor(); } else if (event.key === 'Enter' && event.target.tagName !== 'BUTTON') { event.preventDefault(); void commitInlineEditor(); } }); // Any left click outside the box (map, another marker, the toolbar…) // commits the open edit. The click that ends a map pan is not a click. document.addEventListener('click', (event) => { if (!editSession || event.button !== 0) return; const { target } = event; if (!(target instanceof Node)) return; if (inlineBox.contains(target) || markerContextMenu.contains(target)) return; if (editedLeafletMarker(editSession)?.getElement()?.contains(target)) return; if (map.getContainer().contains(target) && map.dragging?.moved?.()) return; void commitInlineEditor(); }, true); // --- new markers: right-click menu / drop click ---------------------- const startMarkerDraft = (m, latlng, category) => { const point = normalizedPoint(m, latlng); if (!point) { showMarkerStatus('Click inside the selected map to place the marker.', true); return false; } setMarkerDropping(false); const draft = { id: `draft-${Date.now()}`, mapId: m.id, mapName: m.name, x: point[0], y: point[1], category, label: categoryLabel(category), source: 'User marker', }; const draftMarker = L.marker(latlng, { icon: createMarkerIcon(draft), pane: 'semantic-markers', draggable: true, keyboard: false, zIndexOffset: 12000, }).addTo(map); const session = { id: draft.id, isNew: true, draft, draftMarker, busy: false }; draftMarker.on('drag', () => syncInlinePopup(session, draftMarker.getLatLng())); draftMarker.on('dragend', (dragEvent) => { const next = normalizedPoint(m, dragEvent.target.getLatLng()); if (!next) { dragEvent.target.setLatLng([ m.origin[1] + draft.y * m.size[1], m.origin[0] + draft.x * m.size[0], ]); syncInlinePopup(session, dragEvent.target.getLatLng()); showMarkerStatus('Keep the marker inside the selected map.', true); return; } draft.x = next[0]; draft.y = next[1]; }); openSession(session); showMarkerStatus('Name the marker, then click anywhere else to save it.'); return true; }; // Smallest map under the pointer wins (Dorms beats Customs), preferring // maps whose tiles are actually showing at this zoom; the map being edited // wins outright while the pointer is inside it. const mapAtLatLng = (latlng) => { const selected = markerEditing.active ? byId.get(markerEditing.selectedMapId) : null; if (selected && normalizedPoint(selected, latlng)) return selected; const containing = detail .filter((m) => normalizedPoint(m, latlng)) .sort((a, b) => a.size[0] * a.size[1] - b.size[0] * b.size[1]); return containing.find((m) => map.getZoom() >= m.minZoom) ?? containing[0] ?? null; }; let contextTarget = null; const contextHeader = document.createElement('div'); contextHeader.className = 'context-menu-header'; markerContextMenu.appendChild(contextHeader); const knownGroups = new Set(groups.map((group) => group.id)); const menuGroups = [...groups, { id: '__other', label: 'Other' }]; for (const group of menuGroups) { const categories = editorCategories.filter((category) => { const own = categoryConfig(category).group; return (knownGroups.has(own) ? own : '__other') === group.id; }); if (!categories.length) continue; const heading = document.createElement('div'); heading.className = 'context-menu-group'; heading.textContent = group.label; markerContextMenu.appendChild(heading); for (const category of categories) { const settings = categoryConfig(category); const item = document.createElement('button'); item.type = 'button'; item.setAttribute('role', 'menuitem'); item.dataset.category = category; const swatch = document.createElement('span'); swatch.className = 'marker-category-swatch'; swatch.style.background = safeColor(settings.color); swatch.textContent = settings.symbol ?? '•'; const text = document.createElement('span'); text.textContent = categoryLabel(category); item.append(swatch, text); item.addEventListener('click', () => chooseContextCategory(category)); markerContextMenu.appendChild(item); } } function hideContextMenu() { markerContextMenu.hidden = true; contextTarget = null; } const showContextMenu = (event) => { hideContextMenu(); const m = mapAtLatLng(event.latlng); if (!m) return; contextTarget = { m, latlng: event.latlng }; contextHeader.textContent = `Add marker · ${m.name}`; markerContextMenu.hidden = false; const { clientX, clientY } = event.originalEvent; const margin = 8; const left = Math.min(clientX, window.innerWidth - markerContextMenu.offsetWidth - margin); const top = Math.min(clientY, window.innerHeight - markerContextMenu.offsetHeight - margin); markerContextMenu.style.left = `${Math.max(margin, left)}px`; markerContextMenu.style.top = `${Math.max(margin, top)}px`; markerContextMenu.querySelector('button')?.focus({ preventScroll: true }); }; const chooseContextCategory = (category) => { const target = contextTarget; hideContextMenu(); if (!target) return; const { m, latlng } = target; if (!markerEditing.active || markerEditing.selectedMapId !== m.id) { selectTarget(m); if (!markerEditing.active) openMarkerEditor(m); } if (!markerEditing.active) return; startMarkerDraft(m, latlng, category); }; if (markerEditingEnabled) { map.on('contextmenu', showContextMenu); map.on('movestart zoomstart', hideContextMenu); window.addEventListener('resize', hideContextMenu); document.addEventListener('pointerdown', (event) => { if (!markerContextMenu.hidden && !markerContextMenu.contains(event.target)) hideContextMenu(); }, true); markerContextMenu.addEventListener('keydown', (event) => { const items = [...markerContextMenu.querySelectorAll('button')]; const index = items.indexOf(document.activeElement); if (event.key === 'Escape') { event.preventDefault(); hideContextMenu(); } else if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { event.preventDefault(); const step = event.key === 'ArrowDown' ? 1 : -1; items[(index + step + items.length) % items.length]?.focus({ preventScroll: true }); } }); } const showStatus = (message, isError = false) => { status.textContent = message; status.dataset.error = String(isError); }; const writeGeometry = (geometry) => { xInput.value = (geometry.center.lng / world.overallScale).toFixed(3); yInput.value = (geometry.center.lat / world.overallScale).toFixed(3); widthInput.value = (geometry.width / world.overallScale).toFixed(3); heightInput.value = (geometry.height / world.overallScale).toFixed(3); aspectOutput.textContent = `Aspect ratio ${(geometry.width / geometry.height).toFixed(3)}:1`; }; const setPreviewGeometry = (m, geometry) => { const normalized = { ...geometry, center: L.latLng(geometry.center) }; previewGeometry.set(m.id, normalized); updatePreviewTransform(m); editor.marker?.setLatLng(normalized.center); editor.outline?.setBounds(rectAt(normalized)); writeGeometry(normalized); }; const clearEditorLayers = () => { if (editor.marker) map.removeLayer(editor.marker); if (editor.outline) map.removeLayer(editor.outline); editor.marker = null; editor.outline = null; }; const resetPreview = (m) => { if (!m) return; previewGeometry.set(m.id, geometryOf(m)); updatePreviewTransform(m); }; const closeEditor = () => { const m = byId.get(editor.selectedId); resetPreview(m); restoreMapAppearance(m); clearEditorLayers(); editor.active = false; editorPanel.hidden = true; editButton.setAttribute('aria-pressed', 'false'); showStatus(''); }; const openEditor = (m) => { if (!mapEditingEnabled || !m || m.base) return; if (trimEditor.active) closeTrimEditor(); if (markerEditing.active) closeMarkerEditor(); const previous = byId.get(editor.selectedId); if (previous && previous.id !== m.id) { resetPreview(previous); restoreMapAppearance(previous); } clearEditorLayers(); editor.selectedId = m.id; editor.active = true; editorPanel.hidden = false; editButton.disabled = false; editButton.setAttribute('aria-pressed', 'true'); editorName.textContent = m.name; showStatus('Unsaved changes stay in this preview until you save.'); setLayerSource(m, false); const geometry = previewGeometry.get(m.id) ?? geometryOf(m); editor.outline = L.rectangle(rectAt(geometry), { color: '#ffe66d', weight: 2, dashArray: '8 7', fill: false, interactive: false, }).addTo(map); editor.marker = L.marker(geometry.center, { draggable: true, zIndexOffset: 10000, icon: L.divIcon({ className: 'placement-anchor', iconSize: [28, 28] }), }).addTo(map); editor.marker.on('drag', (event) => setPreviewGeometry(m, { ...previewGeometry.get(m.id), center: event.target.getLatLng(), })); editor.marker.on('dragend', () => showStatus('Ready to save and rebuild.')); writeGeometry(geometry); panes.get(m.id).style.opacity = '0.5'; const inside = insidePanes.get(m.id); if (inside) inside.style.display = 'none'; focus(m.id); }; const selectTarget = (m) => { const mode = editor.active ? 'placement' : (trimEditor.active ? 'trim' : (markerEditing.active ? 'markers' : null)); if (editor.active) closeEditor(); if (trimEditor.active) closeTrimEditor(); if (markerEditing.active) closeMarkerEditor(); editor.selectedId = m.base ? null : m.id; trimEditor.selectedId = m.base ? null : m.id; markerEditing.selectedMapId = m.base ? null : m.id; editButton.disabled = !mapEditingEnabled || !!m.base; trimButton.disabled = !mapEditingEnabled || !!m.base; markerEditButton.disabled = !markerEditingEnabled || !!m.base; buttons.forEach((b) => { b.dataset.selected = String(b.dataset.id === m.id); }); overviewButton.dataset.selected = String(!!m.base); if (mapEditingEnabled && !m.base && mode === 'placement') openEditor(m); if (mapEditingEnabled && !m.base && mode === 'trim') openTrimEditor(m); if (markerEditingEnabled && !m.base && mode === 'markers') openMarkerEditor(m); }; const roots = detail.filter((m) => !m.parent); const orderedDetail = roots.flatMap((m) => [ m, ...detail.filter((child) => child.parent === m.id), ]); const orderedIds = new Set(orderedDetail.map((m) => m.id)); orderedDetail.push(...detail.filter((m) => !orderedIds.has(m.id))); const buttons = orderedDetail.map((m) => { const b = document.createElement('button'); b.textContent = m.name; b.dataset.id = m.id; b.dataset.subMap = String(!!m.parent); b.addEventListener('click', () => { selectTarget(m); map.flyToBounds(familyViewRect(m), { padding: [24, 24], duration: 0.7 }); // A phone has no hover: picking a map gives the screen back to the map. if (window.matchMedia('(max-width: 640px)').matches) setPanelPinned(false); }); list.appendChild(b); return b; }); overviewButton.addEventListener('click', () => { selectTarget(base); focus(base.id); map.flyToBounds(familyViewRect(base), { padding: [24, 24], duration: 0.7 }); }); editButton.setAttribute('aria-pressed', 'false'); trimButton.setAttribute('aria-pressed', 'false'); markerEditButton.setAttribute('aria-pressed', 'false'); exportButton.addEventListener('click', async () => { exportButton.disabled = true; exportStatus.dataset.error = 'false'; exportStatus.textContent = 'Building static ZIP…'; try { const response = await fetch('api/export', { method: 'POST' }); const result = await response.json().catch(() => ({})); if (!response.ok) throw new Error(result.error || `Export failed (${response.status})`); const sizeMiB = (Number(result.zipBytes) / 1024 / 1024).toFixed(1); exportStatus.textContent = `Created ${result.fileName} (${sizeMiB} MiB, ${result.fileCount} files).`; const download = document.createElement('a'); download.href = `${result.download}?v=${Date.now()}`; download.download = result.fileName; document.body.appendChild(download); download.click(); download.remove(); } catch (error) { exportStatus.dataset.error = 'true'; exportStatus.textContent = error.message; } finally { exportButton.disabled = false; } }); editButton.addEventListener('click', () => { if (editor.active) closeEditor(); else openEditor(byId.get(editor.selectedId)); }); trimButton.addEventListener('click', () => { if (trimEditor.active) closeTrimEditor(); else openTrimEditor(byId.get(trimEditor.selectedId)); }); markerEditButton.addEventListener('click', () => { if (markerEditing.active) closeMarkerEditor(); else openMarkerEditor(byId.get(markerEditing.selectedMapId)); }); const applyInputs = () => { const m = byId.get(editor.selectedId); const cx = Number(xInput.value); const cy = Number(yInput.value); const width = Number(widthInput.value); const height = Number(heightInput.value); if (!m || ![cx, cy, width, height].every(Number.isFinite) || width <= 0 || height <= 0) return; setPreviewGeometry(m, { center: L.latLng(cy * world.overallScale, cx * world.overallScale), width: width * world.overallScale, height: height * world.overallScale, }); showStatus('Ready to save and rebuild.'); }; xInput.addEventListener('input', applyInputs); yInput.addEventListener('input', applyInputs); widthInput.addEventListener('input', applyInputs); heightInput.addEventListener('input', applyInputs); resetButton.addEventListener('click', () => { const m = byId.get(editor.selectedId); if (!m) return; setPreviewGeometry(m, geometryOf(m)); showStatus('Reset to the last saved center.'); }); saveButton.addEventListener('click', async () => { const m = byId.get(editor.selectedId); const geometry = m && previewGeometry.get(m.id); if (!m || !geometry) return; saveButton.disabled = true; resetButton.disabled = true; showStatus('Saving maps.json and rebuilding this map…'); try { const response = await fetch('api/placement', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: m.id, cx: geometry.center.lng / world.overallScale, cy: geometry.center.lat / world.overallScale, w: geometry.width / world.overallScale, h: geometry.height / world.overallScale, }), }); const responseText = await response.text(); let result; try { result = JSON.parse(responseText); } catch { result = {}; } if (!response.ok) throw new Error( result.error || 'This server is read-only; start it with server/run.ps1 -Editable', ); showStatus('Saved. Reloading rebuilt tiles…'); const z = Math.round(map.getZoom() * 4) / 4; history.replaceState( null, '', `#${z}/${Math.round(geometry.center.lat)}/${Math.round(geometry.center.lng)}`, ); location.reload(); } catch (error) { showStatus(`Save failed: ${error.message}`, true); saveButton.disabled = false; resetButton.disabled = false; } }); // --- playable-area trim editor --------------------------------------- const showTrimStatus = (message, isError = false) => { trimStatus.textContent = message; trimStatus.dataset.error = String(isError); }; const trimLatLngs = (m) => trimEditor.points.map(([x, y]) => L.latLng( m.origin[1] + y * m.size[1], m.origin[0] + x * m.size[0], )); const normalizedPoint = (m, latlng) => { const x = (latlng.lng - m.origin[0]) / m.size[0]; const y = (latlng.lat - m.origin[1]) / m.size[1]; if (x < 0 || x > 1 || y < 0 || y > 1) return null; return [Math.max(0, Math.min(1, x)), Math.max(0, Math.min(1, y))]; }; const updateTrimUI = () => { const count = trimEditor.points.length; trimPointCount.textContent = `${count} point${count === 1 ? '' : 's'}`; trimTransparency.value = String(Math.round(trimEditor.transparency * 100)); trimTransparencyValue.textContent = `${Math.round(trimEditor.transparency * 100)}%`; trimUndo.disabled = count === 0; trimClear.disabled = count === 0; trimSave.disabled = count === 1 || count === 2; }; const clearTrimEditorLayers = () => { trimEditor.markers.forEach((marker) => map.removeLayer(marker)); trimEditor.markers = []; if (trimEditor.outline) map.removeLayer(trimEditor.outline); trimEditor.outline = null; }; const updateTrimShape = (m) => { const latlngs = trimLatLngs(m); if (trimEditor.outline) { const shape = latlngs.length >= 3 ? [...latlngs, latlngs[0]] : latlngs; trimEditor.outline.setLatLngs(shape); } renderTrim(m, trimEditor.points, trimEditor.transparency); updateTrimUI(); }; const rebuildTrimEditorLayers = (m) => { clearTrimEditorLayers(); const latlngs = trimLatLngs(m); if (latlngs.length) { const shape = latlngs.length >= 3 ? [...latlngs, latlngs[0]] : latlngs; trimEditor.outline = L.polyline(shape, { color: '#ffcf4a', weight: 2, dashArray: '7 6', interactive: false, }).addTo(map); } trimEditor.markers = latlngs.map((latlng, index) => { const marker = L.marker(latlng, { draggable: true, zIndexOffset: 11000, icon: L.divIcon({ className: 'trim-vertex', iconSize: [14, 14] }), }).addTo(map); marker.on('drag', (event) => { const point = normalizedPoint(m, event.target.getLatLng()); if (!point) return; trimEditor.points[index] = point; updateTrimShape(m); }); marker.on('dragend', () => showTrimStatus('Ready to save.')); return marker; }); updateTrimShape(m); }; function closeTrimEditor() { const m = byId.get(trimEditor.selectedId); clearTrimEditorLayers(); trimEditor.active = false; trimPanel.hidden = true; trimButton.setAttribute('aria-pressed', 'false'); restoreMapAppearance(m); showTrimStatus(''); } function openTrimEditor(m) { if (!mapEditingEnabled || !m || m.base) return; if (editor.active) closeEditor(); if (markerEditing.active) closeMarkerEditor(); clearTrimEditorLayers(); const saved = savedTrim(m); trimEditor.selectedId = m.id; trimEditor.active = true; trimEditor.points = saved.points; trimEditor.transparency = saved.transparency; trimPanel.hidden = false; trimButton.disabled = false; trimButton.setAttribute('aria-pressed', 'true'); trimName.textContent = m.name; setLayerSource(m, false); showTrimStatus(saved.points.length ? 'Drag existing points or click the map to add more.' : 'Add at least three points around the playable area.'); rebuildTrimEditorLayers(m); focus(m.id); } trimTransparency.addEventListener('input', () => { const m = byId.get(trimEditor.selectedId); if (!m) return; trimEditor.transparency = Number(trimTransparency.value) / 100; renderTrim(m, trimEditor.points, trimEditor.transparency); updateTrimUI(); showTrimStatus('Ready to save.'); }); trimUndo.addEventListener('click', () => { const m = byId.get(trimEditor.selectedId); if (!m || !trimEditor.points.length) return; trimEditor.points.pop(); rebuildTrimEditorLayers(m); showTrimStatus(trimEditor.points.length >= 3 ? 'Ready to save.' : 'Add at least three points.'); }); trimClear.addEventListener('click', () => { const m = byId.get(trimEditor.selectedId); if (!m) return; trimEditor.points = []; rebuildTrimEditorLayers(m); showTrimStatus('Trim cleared. Save to restore the full map.'); }); trimSave.addEventListener('click', async () => { const m = byId.get(trimEditor.selectedId); if (!m || (trimEditor.points.length > 0 && trimEditor.points.length < 3)) return; trimSave.disabled = true; showTrimStatus('Saving and rendering a permanent trimmed copy…'); try { const response = await fetch('api/trim', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: m.id, points: trimEditor.points, outsideTransparency: trimEditor.transparency, }), }); const responseText = await response.text(); let result; try { result = JSON.parse(responseText); } catch { result = {}; } if (!response.ok) throw new Error( result.error || 'This server is read-only; start it with server/run.ps1 -Editable', ); m.trim = result.trim; m.version = result.map.version; m.trimmedVersion = result.map.trimmedVersion; showTrimStatus('Saved. Loading the permanent trimmed tiles…'); closeTrimEditor(); } catch (error) { showTrimStatus(`Save failed: ${error.message}`, true); } finally { updateTrimUI(); } }); map.on('click', (event) => { if (markerEditing.active && markerEditing.dropping) { const m = byId.get(markerEditing.selectedMapId); if (!m) return; const category = editorCategories.includes('poi') ? 'poi' : editorCategories[0]; startMarkerDraft(m, event.latlng, category); return; } if (!trimEditor.active) return; const m = byId.get(trimEditor.selectedId); const point = m && normalizedPoint(m, event.latlng); if (!m || !point) { showTrimStatus('Click inside the selected map to add a point.', true); return; } trimEditor.points.push(point); rebuildTrimEditorLayers(m); showTrimStatus(trimEditor.points.length >= 3 ? 'Ready to save.' : 'Add at least three points.'); }); const updateAllTrimClips = () => { if (!trimEditor.active) return; const m = byId.get(trimEditor.selectedId); if (m && trimEditor.points.length >= 3) updateTrimClip(m, trimEditor.points); }; const syncUI = () => { const c = map.getCenter(); // Smallest non-base map containing the centre wins -- Dorms beats Customs. const hit = markerZoomVisible() ? world.maps .filter((m) => !m.base && viewContains(m, c) && map.getZoom() >= m.minZoom) .sort((a, b) => a.size[0] * a.size[1] - b.size[0] * b.size[1])[0] : null; buttons.forEach((b) => b.setAttribute( 'aria-current', String(!!hit && hit.id === b.dataset.id))); overviewButton.setAttribute('aria-current', String(!hit)); focus(editor.active ? editor.selectedId : (trimEditor.active ? trimEditor.selectedId : (markerEditing.active ? markerEditing.selectedMapId : hit?.id))); const z = Math.round(map.getZoom() * 4) / 4; history.replaceState(null, '', `#${z}/${Math.round(c.lat)}/${Math.round(c.lng)}`); }; map.on('moveend zoomend', syncUI); map.on('move zoom zoomend', () => { updatePreviewTransforms(); updateAllTrimClips(); }); // --- detail / performance mode --------------------------------------- const qualityButton = document.getElementById('quality-toggle'); const qualityLabels = { auto: 'Auto', fast: 'Fast', sharp: 'Sharp' }; const effective = fastMode ? 'fast' : (DENSITY_BOOST ? 'sharp' : 'balanced'); qualityButton.textContent = `Detail: ${qualityLabels[qualityMode]}` + (qualityMode === 'auto' ? ` (${effective})` : ''); qualityButton.title = 'Fast: fewer, lighter tiles for weak devices and slow connections. ' + 'Sharp: denser tiles for high-DPI screens. Auto picks from the hardware. Reloads the page.'; qualityButton.addEventListener('click', () => { const next = QUALITY_MODES[(QUALITY_MODES.indexOf(qualityMode) + 1) % QUALITY_MODES.length]; localStorage.setItem(QUALITY_KEY, next); location.reload(); // tile size and layer options are fixed at creation }); const h = readHash(); if (h) map.setView([h.y, h.x], h.z); else map.fitBounds(rectOf(base), { padding: [10, 10] }); detail.forEach(restoreMapAppearance); syncUI(); document.getElementById('boot').remove(); // --- warm the cache ---------------------------------------------------- /* The overview plus every map's shallow levels are small (z<=5 for the * whole world is a few hundred tiles, a few MB). Fetching them once in the * background means the next visit -- or the next alt-tab from the game -- * paints every map from cache, and only the deep levels of the map you are * actually looking at still touch the network. It also keeps the low-res * underlay permanently warm. Tile responses are immutable for a year, so * repeating this later costs nothing: every fetch is a cache hit. */ const precacheUrls = () => { const urls = []; const ts = world.tileSize; for (const m of world.maps) { const trimmed = usesPermanentTrim(m); const version = trimmed ? m.trimmedVersion : m.version; const template = tileUrl(m, trimmed) + (version ? `?v=${version}` : ''); const top = m.base ? m.maxNativeZoom : Math.min(m.maxNativeZoom, PERF.precacheLevel); for (let z = m.minZoom; z <= top; z += 1) { const s = 2 ** (z - ZMAX); const px = (m.origin[0] - m.cell[0] * world.cellSize) * s; const py = (m.origin[1] - m.cell[1] * world.cellSize) * s; const cw = Math.max(1, Math.round(m.size[0] * s)); const ch = Math.max(1, Math.round(m.size[1] * s)); for (let tx = Math.floor(px / ts); tx < Math.ceil((px + cw) / ts); tx += 1) { for (let ty = Math.floor(py / ts); ty < Math.ceil((py + ch) / ts); ty += 1) { urls.push(template.replace('{z}', z).replace('{x}', tx).replace('{y}', ty)); } } } } return urls; }; const warmTileCache = () => { if (!PERF.precache) return; const stampKey = 'tarkov-precache'; const stamp = world.maps.map((m) => `${m.id}:${m.trimmedVersion ?? m.version}`).join(','); const [lastStamp, lastTime] = (localStorage.getItem(stampKey) ?? '').split('|'); if (lastStamp === stamp && Date.now() - Number(lastTime) < 7 * 86400e3) return; const queue = precacheUrls(); let busy = false; let active = 0; map.on('movestart zoomstart', () => { busy = true; }); map.on('moveend zoomend', () => { busy = false; }); const idle = window.requestIdleCallback ?? ((cb) => setTimeout(cb, 200)); const pump = () => { if (busy) { setTimeout(pump, 500); return; } while (active < 2 && queue.length) { active += 1; fetch(queue.shift(), { priority: 'low' }) .catch(() => {}) .finally(() => { active -= 1; if (queue.length) idle(pump, { timeout: 2000 }); else if (!active) localStorage.setItem(stampKey, `${stamp}|${Date.now()}`); }); } }; // Let the first view land before spending bandwidth on the rest. setTimeout(() => idle(pump, { timeout: 2000 }), 4000); }; warmTileCache(); // --- service worker ----------------------------------------------------- /* Offline and instant-start for the read-only viewer. The authoring server * is excluded: its whole point is seeing a rebuild immediately, and a * cached shell would get in the way. Browsers only allow service workers * on HTTPS or localhost, so a plain-HTTP LAN address silently skips this * and relies on the ordinary HTTP cache, which the warm-up above fills. */ if ('serviceWorker' in navigator) { if (mapEditingEnabled) { navigator.serviceWorker.getRegistrations() .then((registrations) => registrations.forEach((r) => r.unregister())) .catch(() => {}); } else { navigator.serviceWorker.register('sw.js').then((registration) => { const tell = (worker) => worker?.postMessage({ type: 'tile-versions', versions: world.maps.flatMap((m) => [m.version, m.trimmedVersion]).filter(Boolean), }); tell(registration.active ?? navigator.serviceWorker.controller); navigator.serviceWorker.addEventListener('controllerchange', () => { tell(navigator.serviceWorker.controller); }); }).catch((error) => console.warn('service worker unavailable:', error.message)); } } window.tarkovMap = map; window.tarkovWorld = world; } main().catch((err) => { document.getElementById('boot').textContent = `Failed to load: ${err.message}`; console.error(err); });
Enter or click elsewhere saves · Esc cancels