refactor: trip.html.twig — remove CDN tags, deduplicate JS, use MapUtils.parseGpxFiles
- Remove PhotoSwipe CSS CDN link (now in css-compiled/main.css via Asset Manager)
- Remove MapLibre GL, toGeoJSON, maplibre-utils CDN/local script tags
- Add {% block map_assets %} to register map.css and map.js via Asset Manager
- Remove filter bar IIFE (now initFilterBar in main.js)
- Remove sort toggle IIFE (now initSortButton in main.js)
- Remove local haversineKm and parseGpxFiles functions (now in MapUtils via map.js)
- Update parseGpxFiles call to MapUtils.parseGpxFiles
- Update haversineKm call to MapUtils.haversineKm in Mode B stats
- Remove makePanelToggle helper + calls (now initPanelToggles in main.js)
- Remove back-to-top DOMContentLoaded block (now initBackToTop in main.js)
- Remove PhotoSwipe <script type="module"> block (now initPhotoSwipe + initPhotoStrip in main.js)
This commit is contained in:
@@ -1,7 +1,10 @@
|
||||
{% extends 'partials/base.html.twig' %}
|
||||
|
||||
{% block content %}
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@5/dist/photoswipe.css">
|
||||
{% block map_assets %}
|
||||
{% do assets.addCss('theme://css-compiled/map.css') %}
|
||||
{% do assets.addJs('theme://js/map.js', {group: 'bottom'}) %}
|
||||
{% endblock %}
|
||||
{% set dailies_page = grav.pages.find(page.route ~ '/dailies') %}
|
||||
{% set stories_page = grav.pages.find(page.route ~ '/stories') %}
|
||||
{% set journal_entries = dailies_page ? dailies_page.children.published() : [] %}
|
||||
@@ -244,10 +247,6 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/maplibre-gl@4/dist/maplibre-gl.css">
|
||||
<script src="https://cdn.jsdelivr.net/npm/maplibre-gl@4/dist/maplibre-gl.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/@mapbox/togeojson@0.16.2/togeojson.min.js"></script>
|
||||
<script src="{{ url('theme://js/maplibre-utils.js') }}"></script>
|
||||
<script>
|
||||
var TRIP_ENTRIES = {{ map_entries|json_encode|raw }};
|
||||
var GPX_URLS = {{ gpx_urls|json_encode|raw }};
|
||||
@@ -336,159 +335,14 @@ setTimeout(function () { tripMap.resize(); }, 100);
|
||||
});
|
||||
})();
|
||||
|
||||
(function() {
|
||||
var filterBtns = document.querySelectorAll('.trip-filter-btn');
|
||||
var cards = document.querySelectorAll('[data-type]');
|
||||
var filterEmpty = document.getElementById('feed-filter-empty');
|
||||
|
||||
filterBtns.forEach(function(btn) {
|
||||
btn.addEventListener('click', function() {
|
||||
filterBtns.forEach(function(b) { b.classList.remove('is-active'); b.setAttribute('aria-pressed', 'false'); });
|
||||
btn.classList.add('is-active');
|
||||
btn.setAttribute('aria-pressed', 'true');
|
||||
|
||||
var filter = btn.getAttribute('data-filter');
|
||||
var visible = 0;
|
||||
|
||||
cards.forEach(function(card) {
|
||||
var show = filter === 'all' || card.getAttribute('data-type') === filter;
|
||||
card.style.display = show ? '' : 'none';
|
||||
if (show) visible++;
|
||||
});
|
||||
|
||||
if (filterEmpty) {
|
||||
if (visible === 0) {
|
||||
filterEmpty.textContent = filter === 'story'
|
||||
? 'No stories yet for this trip.'
|
||||
: 'No entries yet.';
|
||||
filterEmpty.style.display = '';
|
||||
} else {
|
||||
filterEmpty.style.display = 'none';
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
})();
|
||||
|
||||
(function() {
|
||||
var sortBtn = document.getElementById('trip-sort-toggle');
|
||||
if (!sortBtn) return;
|
||||
var feed = document.querySelector('.feed');
|
||||
var emptyMsg = document.getElementById('feed-filter-empty');
|
||||
var ascending = true;
|
||||
|
||||
sortBtn.addEventListener('click', function() {
|
||||
ascending = !ascending;
|
||||
var entries = Array.from(feed.querySelectorAll('[data-type]'));
|
||||
entries.reverse().forEach(function(el) { feed.insertBefore(el, emptyMsg); });
|
||||
sortBtn.textContent = ascending ? '↑' : '↓';
|
||||
sortBtn.setAttribute('aria-label', ascending ? 'Sort: oldest first' : 'Sort: newest first');
|
||||
sortBtn.classList.toggle('is-active', !ascending);
|
||||
});
|
||||
})();
|
||||
|
||||
var STATS_GPS = {{ gps_points|json_encode|raw }};
|
||||
var HAS_GPX = {{ has_gpx ? 'true' : 'false' }};
|
||||
|
||||
function haversineKm(lat1, lng1, lat2, lng2) {
|
||||
var R = 6371;
|
||||
var dLat = (lat2 - lat1) * Math.PI / 180;
|
||||
var dLng = (lng2 - lng1) * Math.PI / 180;
|
||||
var a = Math.sin(dLat/2)*Math.sin(dLat/2) +
|
||||
Math.cos(lat1*Math.PI/180)*Math.cos(lat2*Math.PI/180)*
|
||||
Math.sin(dLng/2)*Math.sin(dLng/2);
|
||||
return R * 2 * Math.asin(Math.sqrt(a));
|
||||
}
|
||||
|
||||
function parseGpxFiles(urls, callback) {
|
||||
var pending = urls.length;
|
||||
var fileResults = new Array(urls.length);
|
||||
if (pending === 0) { callback({ error: 'no files' }); return; }
|
||||
urls.forEach(function(url, idx) {
|
||||
fetch(url)
|
||||
.then(function(r) { return r.text(); })
|
||||
.then(function(text) {
|
||||
var xml = new DOMParser().parseFromString(text, 'text/xml');
|
||||
var trkpts = xml.querySelectorAll('trkpt');
|
||||
var pts = [];
|
||||
trkpts.forEach(function(pt) {
|
||||
var eleEl = pt.querySelector('ele');
|
||||
var timeEl = pt.querySelector('time');
|
||||
pts.push({
|
||||
lat: parseFloat(pt.getAttribute('lat')),
|
||||
lon: parseFloat(pt.getAttribute('lon')),
|
||||
ele: eleEl ? parseFloat(eleEl.textContent) : NaN,
|
||||
time: timeEl ? timeEl.textContent : null
|
||||
});
|
||||
});
|
||||
fileResults[idx] = pts;
|
||||
pending--;
|
||||
if (pending === 0) { computeAndCallback(); }
|
||||
})
|
||||
.catch(function(err) {
|
||||
console.warn('GPX load failed:', url, err);
|
||||
fileResults[idx] = [];
|
||||
pending--;
|
||||
if (pending === 0) { computeAndCallback(); }
|
||||
});
|
||||
});
|
||||
|
||||
function computeAndCallback() {
|
||||
var totalDistance = 0, totalEleGain = 0, totalEleLoss = 0;
|
||||
var globalHighest = NaN, globalLowest = NaN, totalMovingTime = 0;
|
||||
|
||||
fileResults.forEach(function(pts) {
|
||||
if (!pts || pts.length < 2) return;
|
||||
for (var i = 1; i < pts.length; i++) {
|
||||
var p0 = pts[i-1], p1 = pts[i];
|
||||
var d = haversineKm(p0.lat, p0.lon, p1.lat, p1.lon);
|
||||
totalDistance += d;
|
||||
|
||||
if (!isNaN(p0.ele) && !isNaN(p1.ele)) {
|
||||
var dEle = p1.ele - p0.ele;
|
||||
if (dEle > 0) totalEleGain += dEle;
|
||||
if (dEle < 0) totalEleLoss += (-dEle);
|
||||
if (isNaN(globalHighest) || p1.ele > globalHighest) globalHighest = p1.ele;
|
||||
if (isNaN(globalLowest) || p1.ele < globalLowest) globalLowest = p1.ele;
|
||||
}
|
||||
|
||||
if (p0.time && p1.time) {
|
||||
var dtHrs = (Date.parse(p1.time) - Date.parse(p0.time)) / 3600000;
|
||||
if (dtHrs > 0) {
|
||||
var speed = d / dtHrs;
|
||||
if (speed >= 1) totalMovingTime += dtHrs;
|
||||
}
|
||||
}
|
||||
}
|
||||
// include first point of each file in elevation range
|
||||
if (pts.length > 0 && !isNaN(pts[0].ele)) {
|
||||
if (isNaN(globalHighest) || pts[0].ele > globalHighest) globalHighest = pts[0].ele;
|
||||
if (isNaN(globalLowest) || pts[0].ele < globalLowest) globalLowest = pts[0].ele;
|
||||
}
|
||||
});
|
||||
|
||||
var avgSpeed = totalMovingTime > 0 ? totalDistance / totalMovingTime : 0;
|
||||
var movHours = Math.floor(totalMovingTime);
|
||||
var movMins = Math.round((totalMovingTime - movHours) * 60);
|
||||
if (movMins === 60) { movHours++; movMins = 0; }
|
||||
|
||||
callback({
|
||||
distance: totalDistance,
|
||||
eleGain: totalEleGain,
|
||||
eleLoss: totalEleLoss,
|
||||
highest: globalHighest,
|
||||
lowest: globalLowest,
|
||||
movingTime: movHours + ':' + (movMins < 10 ? '0' : '') + movMins,
|
||||
avgSpeed: avgSpeed
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
(function() {
|
||||
var distEl = document.getElementById('stat-distance');
|
||||
|
||||
if (HAS_GPX) {
|
||||
parseGpxFiles(GPX_URLS, function(result) {
|
||||
MapUtils.parseGpxFiles(GPX_URLS, function(result) {
|
||||
// Mode A: update distance stat
|
||||
if (distEl) {
|
||||
distEl.textContent = result.distance > 0 ? Math.round(result.distance).toLocaleString() : '—';
|
||||
@@ -510,7 +364,7 @@ function parseGpxFiles(urls, callback) {
|
||||
// Mode B: haversine between entry points
|
||||
var total = 0;
|
||||
for (var i = 1; i < STATS_GPS.length; i++) {
|
||||
total += haversineKm(
|
||||
total += MapUtils.haversineKm(
|
||||
parseFloat(STATS_GPS[i-1][0]), parseFloat(STATS_GPS[i-1][1]),
|
||||
parseFloat(STATS_GPS[i][0]), parseFloat(STATS_GPS[i][1])
|
||||
);
|
||||
@@ -520,108 +374,10 @@ function parseGpxFiles(urls, callback) {
|
||||
}
|
||||
}
|
||||
|
||||
function makePanelToggle(toggleId, blockId) {
|
||||
var toggle = document.getElementById(toggleId);
|
||||
var block = document.getElementById(blockId);
|
||||
if (!toggle || !block) return;
|
||||
toggle.addEventListener('click', function() {
|
||||
var isOpen = block.classList.contains('is-open');
|
||||
block.classList.toggle('is-open', !isOpen);
|
||||
toggle.classList.toggle('is-active', !isOpen);
|
||||
toggle.setAttribute('aria-expanded', isOpen ? 'false' : 'true');
|
||||
});
|
||||
}
|
||||
makePanelToggle('trip-stats-toggle', 'trip-stats-block');
|
||||
makePanelToggle('trip-cycling-toggle', 'trip-cycling-block');
|
||||
|
||||
// Close buttons inside panels (mobile only via CSS)
|
||||
document.querySelectorAll('.trip-panel-close').forEach(function(btn) {
|
||||
var toggleBtn = document.getElementById(btn.getAttribute('data-toggle'));
|
||||
if (toggleBtn) btn.addEventListener('click', function() { toggleBtn.click(); });
|
||||
});
|
||||
})();
|
||||
|
||||
/* ── Back to top ─────────────────────────────────────────── */
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
var btn = document.getElementById('trip-totop');
|
||||
if (!btn) return;
|
||||
var threshold = window.innerHeight * 0.8;
|
||||
var shown = false;
|
||||
btn.addEventListener('click', function () {
|
||||
history.pushState(null, '', window.location.pathname + window.location.search);
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
});
|
||||
window.addEventListener('scroll', function () {
|
||||
var shouldShow = window.scrollY > threshold;
|
||||
if (shouldShow !== shown) {
|
||||
shown = shouldShow;
|
||||
btn.classList.toggle('is-visible', shown);
|
||||
}
|
||||
}, { passive: true });
|
||||
});
|
||||
</script>
|
||||
|
||||
<button class="story-totop" id="trip-totop" aria-label="Back to top">↑ Top</button>
|
||||
|
||||
<script type="module">
|
||||
import PhotoSwipeLightbox from 'https://cdn.jsdelivr.net/npm/photoswipe@5/dist/photoswipe-lightbox.esm.min.js';
|
||||
const lightbox = new PhotoSwipeLightbox({
|
||||
gallery: '.pswp-gallery',
|
||||
children: 'a.journal-photo-slide',
|
||||
pswpModule: () => import('https://cdn.jsdelivr.net/npm/photoswipe@5/dist/photoswipe.esm.min.js')
|
||||
});
|
||||
lightbox.on('afterOpen', function () {
|
||||
var pswp = lightbox.pswp;
|
||||
var keyDir = 0;
|
||||
var clearTimer = null;
|
||||
function onKey(e) {
|
||||
if (e.key === 'ArrowRight') keyDir = 1;
|
||||
else if (e.key === 'ArrowLeft') keyDir = -1;
|
||||
else keyDir = 0;
|
||||
}
|
||||
document.addEventListener('keydown', onKey, true);
|
||||
pswp.on('change', function () {
|
||||
if (!keyDir) return;
|
||||
var dir = keyDir;
|
||||
keyDir = 0;
|
||||
var el = pswp.currSlide && pswp.currSlide.container;
|
||||
if (!el) return;
|
||||
el.classList.remove('pswp-key-from-left', 'pswp-key-from-right');
|
||||
el.offsetWidth;
|
||||
el.classList.add(dir > 0 ? 'pswp-key-from-right' : 'pswp-key-from-left');
|
||||
clearTimeout(clearTimer);
|
||||
clearTimer = setTimeout(function () { el.classList.remove('pswp-key-from-left', 'pswp-key-from-right'); }, 400);
|
||||
});
|
||||
pswp.on('close', function () {
|
||||
document.removeEventListener('keydown', onKey, true);
|
||||
clearTimeout(clearTimer);
|
||||
});
|
||||
});
|
||||
lightbox.init();
|
||||
|
||||
document.querySelectorAll('.journal-photo-wrap').forEach(function (wrap) {
|
||||
var strip = wrap.querySelector('.journal-photo-strip');
|
||||
var slides = Array.from(strip.querySelectorAll('a.journal-photo-slide'));
|
||||
var expandBtn = wrap.querySelector('.journal-photo-expand');
|
||||
var article = wrap.closest('article');
|
||||
var dots = article ? Array.from(article.querySelectorAll('.journal-photo-dot')) : [];
|
||||
var visibleIdx = 0;
|
||||
|
||||
var io = new IntersectionObserver(function (entries) {
|
||||
entries.forEach(function (e) {
|
||||
if (!e.isIntersecting) return;
|
||||
visibleIdx = slides.indexOf(e.target);
|
||||
dots.forEach(function (d) { d.classList.remove('is-active'); });
|
||||
if (dots[visibleIdx]) dots[visibleIdx].classList.add('is-active');
|
||||
});
|
||||
}, { root: strip, threshold: 0.5 });
|
||||
slides.forEach(function (s) { io.observe(s); });
|
||||
|
||||
if (expandBtn && slides.length) {
|
||||
expandBtn.addEventListener('click', function () {
|
||||
slides[visibleIdx].dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }));
|
||||
});
|
||||
}
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
||||
Reference in New Issue
Block a user