Действия

MediaWiki

MediaWiki:Common.js

Материал из Много троп

Замечание: Возможно, после публикации вам придётся очистить кэш своего браузера, чтобы увидеть изменения.

  • Firefox / Safari: Удерживая клавишу Shift, нажмите на панели инструментов Обновить либо нажмите Ctrl+F5 или Ctrl+R (⌘+R на Mac)
  • Google Chrome: Нажмите Ctrl+Shift+R (⌘+Shift+R на Mac)
  • Edge: Удерживая Ctrl, нажмите Обновить либо нажмите Ctrl+F5
  • Opera: Нажмите Ctrl+F5.
/* Размещённый здесь код JavaScript будет загружаться пользователям при обращении к каждой странице */

$(function () {
    $('.hidden-iframe-container').each(function () {
        const container = this;
        const iframe = container.querySelector('.hidden-iframe');

        if (!iframe) {
            return;
        }

        let loaded = false;

        // Считаем iframe загруженным после события load
        iframe.addEventListener('load', function () {
            loaded = true;

            // Небольшая задержка перед отображением
            setTimeout(function () {
                container.style.display = '';
            }, 3000); // 3000 мс = 3 секунды
        });

        // Если iframe не загрузился за 5 секунд, оставляем его скрытым
        setTimeout(function () {
            if (!loaded) {
                container.remove();
                // Или вместо удаления:
                // container.style.display = 'none';
            }
        }, 5000);
    });
});

mw.hook('wikipage.content').add(function ($content) {
    const button = document.getElementById('download-gpx');
    const dataElement = document.getElementById('route-data');

    if (!button || !dataElement) {
        return;
    }

    function downloadGpx() {
        try {
            const data = JSON.parse(dataElement.textContent.trim());
            const gpx = geoJsonToGpx(data);

            const blob = new Blob([gpx], {
                type: 'application/gpx+xml'
            });

            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');

            link.href = url;
            link.download = 'route.gpx';
            document.body.appendChild(link);
            link.click();
            link.remove();

            URL.revokeObjectURL(url);
        } catch (error) {
            console.error('Не удалось создать GPX-файл:', error);
        }
    }

    button.addEventListener('click', downloadGpx);
    button.addEventListener('keydown', function (event) {
        if (event.key === 'Enter' || event.key === ' ') {
            event.preventDefault();
            downloadGpx();
        }
    });
});

function geoJsonToGpx(geojson) {
    const features = geojson.type === 'FeatureCollection'
        ? geojson.features
        : [geojson];

    const points = [];

    for (const feature of features) {
        const geometry = feature.geometry;

        if (!geometry) {
            continue;
        }

        if (geometry.type === 'LineString') {
            for (const coordinate of geometry.coordinates) {
                points.push(coordinate);
            }
        } else if (geometry.type === 'Point') {
            points.push(geometry.coordinates);
        } else if (geometry.type === 'MultiLineString') {
            for (const line of geometry.coordinates) {
                for (const coordinate of line) {
                    points.push(coordinate);
                }
            }
        }
    }

    const trackPoints = points.map(function (coordinate) {
        const longitude = coordinate[0];
        const latitude = coordinate[1];

        return `      <trkpt lat="${latitude}" lon="${longitude}"></trkpt>`;
    }).join('\n');

    return `<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1"
     creator="MediaWiki"
     xmlns="http://www.topografix.com/GPX/1/1">
  <trk>
    <name>Маршрут</name>
    <trkseg>
${trackPoints}
    </trkseg>
  </trk>
</gpx>`;
}