Put the filters on every list and place page, and count their numbers from the page
Mirror to forge / mirror (push) Canceled after 0s
Validate / validate (push) Canceled after 0s
Validate / history (push) Canceled after 0s
Validate / site (push) Canceled after 0s
Validate / deploy (push) Canceled after 0s

The search and filters bar is on every list, place and the Routes
page with ten or more trails, scoped to that page's set and closed to
start. The number beside each choice is recounted from the page's rows
on every change; a choice that would show nothing is hidden; a filter
that cannot narrow the page is left out. The open panel sits in the
flow and pushes the rows down. Each part of the country has a page of
its own, and the links to the home page "with the filters" are gone.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-17 12:46:08 -07:00
1 parent f467fcb560
commit 1ed0a68991
12 files changed
+906 -212

No files matched your search

+306 -103
View File
@@ -13,7 +13,7 @@
(data-frame), and the drawing gives way to it once it has drawn the tracks. Where
the base map cannot load, the drawing stays. A trail page's map (data-outdoor) is an
outdoor map, with relief and contours, and a switch to the plain one.
3. Trail finder (home page): search, filters, sort, URL query state, map/list highlight
3. The filter bar (home, lists, places, Routes): search, filters, counts, sort, URL state, highlight
4. Copy-credit buttons
Every page works without this script: the list holds every trail and each map
@@ -1452,7 +1452,7 @@
function initSortableLists() {
document.querySelectorAll('.results[data-sortable]').forEach(function (root) {
if (root.querySelector('#entries')) return; /* the finder wires its own list */
if (root.hasAttribute('data-finder')) return; /* the filter bar wires its own list */
var select = root.querySelector('[data-sort-select]');
var current = defaultSortOf(root);
function setSort(key, updateUrl, announce) {
@@ -1468,32 +1468,111 @@
});
}
/* 3. Trail finder (home page) ------------------------------------------------
/* 3. The filter bar --------------------------------------------------------
One bar and one set of panels, on the home page and on every other page
that shows a set of trails large enough to narrow (olt/home.py listing()).
The filters are the attributes every page names: Where, Length, Time,
Season, Terrain, Kind, Walking, Shape and GPX. Each row carries its values
as data-* attributes (olt/home.py entry()). A filter on a facet that a
trail has no value for leaves that trail out, and the note under the
filter (data-missing) says how many trails have no value on file. */
as data-* attributes (olt/home.py entry()), and everything here is worked
out from the rows on the page: which rows show, the number beside each
choice, and which choices and filters are offered at all. A filter on a
facet that a trail has no value for leaves that trail out, and the note
under the filter (data-missing) says how many trails have no value on
file. The state is in the address (?where=…&time=…), so a narrowed page
can be shared, reloaded and gone back to; nothing is kept between pages. */
var MULTI = ['time', 'terrain', 'walking', 'shape', 'gpx'];
var MORE = ['walking', 'shape', 'gpx'];
/* Addresses from before the site had these filters still work. */
var OLD_POLICY = { open: 'free', sold: 'sold', withheld: 'unpublished', unclear: 'elsewhere' };
/* facet-counts:begin — pure, with no page: web/tests/test_filter_counts.py runs this under node.
A row: {search, where: [], km, time, months: [], terrain: [], kind, walking, shape, gpx}.
A state: {words: [], where, min, max (km; max may be Infinity), month, kind, and a list for
each of time, terrain, walking, shape, gpx}. */
var FacetCount = (function () {
var FACETS = ['where', 'length', 'time', 'month', 'terrain', 'kind', 'walking', 'shape', 'gpx'];
function has(list, v) { return list.indexOf(v) !== -1; }
/* Does the row pass the search and every filter but `skip`? Within Time, Terrain, Walking,
Shape and GPX the choices are alternatives: a row with any one of them passes. */
function passes(d, s, skip) {
if (s.words.some(function (w) { return d.search.indexOf(w) === -1; })) return false;
if (skip !== 'where' && s.where && !has(d.where, s.where)) return false;
if (skip !== 'length' && (d.km < s.min || d.km > s.max)) return false;
if (skip !== 'time' && s.time.length && !has(s.time, d.time)) return false;
if (skip !== 'month' && s.month && !has(d.months, s.month)) return false;
if (skip !== 'terrain' && s.terrain.length && !d.terrain.some(function (t) { return has(s.terrain, t); })) return false;
if (skip !== 'kind' && s.kind && d.kind !== s.kind) return false;
if (skip !== 'walking' && s.walking.length && !has(s.walking, d.walking)) return false;
if (skip !== 'shape' && s.shape.length && !has(s.shape, d.shape)) return false;
if (skip !== 'gpx' && s.gpx.length && !has(s.gpx, d.gpx)) return false;
return true;
}
function valuesOf(d, f) {
if (f === 'where') return d.where;
if (f === 'month') return d.months;
if (f === 'terrain') return d.terrain;
return d[f] ? [d[f]] : [];
}
/* The numbers for every choice. Each facet's choices are counted against the search and all
the other facets as they are set, never against the facet's own choice: the number beside a
choice is what choosing it (instead, in Where, Season and Kind; on its own, in a list of
boxes) shows. base[f]: the rows the other facets leave, which is what the facet's "any"
shows. steps: [[value, km]] of the length lists; min[value] counts the rows from that length
up to the chosen longest, max[value] those up to that length from the chosen shortest. */
function count(rows, s, steps) {
var out = { total: 0, base: {}, min: {}, max: {} };
FACETS.forEach(function (f) { out.base[f] = 0; if (f !== 'length') out[f] = {}; });
(steps || []).forEach(function (st) { out.min[st[0]] = 0; out.max[st[0]] = 0; });
rows.forEach(function (d) {
if (passes(d, s, '')) out.total += 1;
FACETS.forEach(function (f) {
if (!passes(d, s, f)) return;
out.base[f] += 1;
if (f === 'length') {
(steps || []).forEach(function (st) {
if (d.km >= st[1] && d.km <= s.max) out.min[st[0]] += 1;
if (d.km <= st[1] && d.km >= s.min) out.max[st[0]] += 1;
});
return;
}
valuesOf(d, f).forEach(function (v) { out[f][v] = (out[f][v] || 0) + 1; });
});
});
return out;
}
return { passes: passes, count: count };
})();
/* facet-counts:end */
function initFinder(form) {
var list = document.getElementById('entries');
var items = Array.prototype.slice.call(list.querySelectorAll('.entry'));
var count = document.getElementById('results-count');
var empty = document.getElementById('empty-state');
var resultsRoot = document.querySelector('.results[data-finder]');
if (!resultsRoot) return;
function split(v) { return (v || '').split(' ').filter(Boolean); }
var rows = Array.prototype.map.call(resultsRoot.querySelectorAll('.entry[data-id]'), function (li) {
var d = li.dataset;
return { li: li, id: d.id, search: d.search || '', where: split(d.where), km: Number(d.km), time: d.time || '',
months: split(d.months), terrain: split(d.terrain), kind: d.kind || '', walking: d.walking || '',
shape: d.shape || '', gpx: d.gpx || '' };
});
var lists = Array.prototype.slice.call(resultsRoot.querySelectorAll('ol.entries'));
var count = resultsRoot.querySelector('.results-count');
var noun = (count && count.dataset.noun) || 'trails';
var empty = resultsRoot.querySelector('.empty-state');
var active = form.querySelector('.filters__active');
var lenHint = document.getElementById('len-hint');
var resultsRoot = list.closest('.results');
var listHead = resultsRoot ? resultsRoot.querySelector('.list-head') : document.querySelector('.list-head');
var listHead = resultsRoot.querySelector('.list-head');
var el = form.elements;
var sort = document.getElementById('sort');
var sort = resultsRoot.querySelector('[data-sort-select]');
var defaultSort = defaultSortOf(resultsRoot);
var more = form.querySelector('.filters__more');
var total = items.length;
var none = form.querySelector('.filters__none');
var fields = Array.prototype.slice.call(form.querySelectorAll('[data-facet]'));
var total = rows.length;
/* The bar: the Filters control opens the panels, and Clear shows only when something is set. */
var toggle = form.querySelector('.filters__toggle');
var panels = form.querySelector('.filters__panels');
@@ -1503,15 +1582,19 @@
if (open) panels.setAttribute('data-open', ''); else panels.removeAttribute('data-open');
if (toggle) toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
}
/* The open panels sit in the page between the bar and the rows, which move down: nothing is
laid over a row. Show the trails (or Escape) closes them and brings the bar, and the first
row under it, back into view. */
function closePanels() {
showPanels(false);
if (toggle) toggle.focus({ preventScroll: true });
if (form.getBoundingClientRect().top < 0) form.scrollIntoView({ block: 'start' });
}
if (toggle) toggle.addEventListener('click', function () { showPanels(!panels.hasAttribute('data-open')); });
/* The open panels lie over the rows: Show the trails, Escape, or a click outside the form closes them. */
var done = form.querySelector('.filters__done');
if (done) done.addEventListener('click', function () { showPanels(false); if (toggle) toggle.focus(); });
if (done) done.addEventListener('click', closePanels);
form.addEventListener('keydown', function (e) {
if (e.key === 'Escape' && panels && panels.hasAttribute('data-open')) { showPanels(false); if (toggle) toggle.focus(); }
});
document.addEventListener('click', function (e) {
if (panels && panels.hasAttribute('data-open') && !form.contains(e.target)) showPanels(false);
if (e.key === 'Escape' && panels && panels.hasAttribute('data-open')) closePanels();
});
/* The count is the one live region. Keep it quiet through the first
@@ -1548,66 +1631,61 @@
var r = form.querySelector('input[name="' + name + '"]:checked');
return r ? r.value : '';
}
function value(field) { return field ? field.value : ''; }
/* The choices of Where and Season as the page wrote them, before any is taken out for
showing nothing: [{value, label, counted, group, def}]. */
function masterOf(select) {
if (!select) return [];
return Array.prototype.map.call(select.options, function (o) {
var group = o.parentNode && o.parentNode.tagName === 'OPTGROUP' ? o.parentNode.label : '';
return { value: o.value, label: o.dataset.label || o.textContent, counted: !!o.dataset.label, group: group,
def: o.value === '' };
});
}
var masters = { where: masterOf(el.where), month: masterOf(el.month), min: [], max: [] };
function read() {
var min = stepKm(el.min.value) || 0;
var max = stepKm(el.max.value) || Infinity;
var minRaw = el.min.value, maxRaw = el.max.value;
var min = stepKm(value(el.min)) || 0;
var max = stepKm(value(el.max)) || Infinity;
var minRaw = value(el.min), maxRaw = value(el.max);
var swapped = min > max;
if (swapped) { var keep = min; min = max; max = keep; keep = minRaw; minRaw = maxRaw; maxRaw = keep; }
var q = value(el.q).trim();
var s = {
q: el.q.value.trim(),
words: el.q.value.trim().toLowerCase().split(/\s+/).filter(Boolean),
where: el.where.value,
q: q,
words: q.toLowerCase().split(/\s+/).filter(Boolean),
where: value(el.where),
min: min,
max: max,
minRaw: minRaw,
maxRaw: maxRaw,
swapped: swapped,
month: el.month ? el.month.value : '',
month: value(el.month),
kind: radio('kind')
};
MULTI.forEach(function (name) { s[name] = checked(name); });
return s;
}
function words(value) { return (value || '').split(' ').filter(Boolean); }
function anyOf(chosen, value) { return !chosen.length || chosen.indexOf(value) !== -1; }
function matches(li, s) {
var d = li.dataset;
if (s.words.some(function (w) { return d.search.indexOf(w) === -1; })) return false;
if (s.where && words(d.where).indexOf(s.where) === -1) return false;
var km = Number(d.km);
if (km < s.min || km > s.max) return false;
if (!anyOf(s.time, d.time)) return false;
if (s.month && words(d.months).indexOf(s.month) === -1) return false;
if (s.terrain.length && !words(d.terrain).some(function (t) { return s.terrain.indexOf(t) !== -1; })) return false;
if (s.kind && d.kind !== s.kind) return false;
if (s.walking.length && !anyOf(s.walking, d.walking)) return false;
if (s.shape.length && !anyOf(s.shape, d.shape)) return false;
if (!anyOf(s.gpx, d.gpx)) return false;
return true;
}
/* A length step's value is "100mi" or "160km": round in its own unit, so the
list offered follows the reader's units. Filtering compares kilometres. */
function stepKm(value) {
var m = /^(\d+(?:\.\d+)?)(mi|km)$/.exec(value || '');
function stepKm(v) {
var m = /^(\d+(?:\.\d+)?)(mi|km)$/.exec(v || '');
return m ? Number(m[1]) * (m[2] === 'mi' ? KM_PER_MI : 1) : 0;
}
function stepLabel(n, unit) {
var km = unit === 'mi' ? n * KM_PER_MI : n;
var other = unit === 'mi' ? fmt.format(Math.round(km)) + ' km' : fmt.format(Math.round(km / KM_PER_MI)) + ' mi';
return fmt.format(n) + ' ' + unit + ' \u00b7 ' + other;
return fmt.format(n) + ' ' + unit + ' · ' + other;
}
/* The value of the step in a list nearest to a length, or '' for none. */
function nearestStep(select, km) {
var best = '', gap = Infinity;
if (!(km > 0)) return best;
Array.prototype.forEach.call(select.options, function (o) {
(masters[select.name] || []).forEach(function (o) {
var k = stepKm(o.value);
if (!k) return;
var d = Math.abs(Math.log(k / km));
@@ -1616,6 +1694,44 @@
return best;
}
/* Write a select's choices from its master list: each with its number, and none that would
show nothing unless it is the one chosen (so it can be unchosen). The options themselves
are taken out, not hidden: a hidden option is not hidden in every browser. */
function renderSelect(select, n) {
if (!select) return;
var chosen = select.value;
var parts = [];
masters[select.name].forEach(function (o) {
var k = o.counted ? (n(o.value) || 0) : null;
if (o.value && k === 0 && o.value !== chosen) return;
parts.push({ o: o, k: k });
});
var sig = parts.map(function (p) { return p.o.value + ':' + p.k; }).join('|');
if (select.getAttribute('data-sig') === sig) return;
select.setAttribute('data-sig', sig);
select.textContent = '';
var groupEl = null;
parts.forEach(function (p) {
var opt = document.createElement('option');
opt.value = p.o.value;
opt.textContent = p.k === null ? p.o.label : p.o.label + ' (' + fmt.format(p.k) + ')';
/* A form's reset picks the option marked as default, or else the first one. */
if (p.o.def) opt.defaultSelected = true;
var parent = select;
if (p.o.group) {
if (!groupEl || groupEl.label !== p.o.group) {
groupEl = document.createElement('optgroup');
groupEl.label = p.o.group;
select.appendChild(groupEl);
}
parent = groupEl;
} else groupEl = null;
parent.appendChild(opt);
});
select.value = chosen;
if (select.value !== chosen) select.value = '';
}
/* Offer round steps in the reader's units. The server writes the mile steps;
a reader who chose kilometres gets the kilometre steps (data-steps-km), and
a chosen step moves to the nearest one in the new list. */
@@ -1625,26 +1741,31 @@
var kind = select.dataset.lengthOptions;
var steps = (select.getAttribute('data-steps-' + unit) || '').split(',').filter(Boolean).map(Number);
var wasKm = stepKm(select.value);
select.textContent = '';
function add(value, text, selected) {
var o = document.createElement('option');
o.value = value;
o.textContent = text;
/* "Any" is the default, so that the form's reset returns to it: a reset
picks the option marked as default, or else the first one. */
if (value === '') o.defaultSelected = true;
if (selected) o.selected = true;
select.appendChild(o);
}
if (kind === 'min') add('', 'Any', false);
var master = [];
if (kind === 'min') master.push({ value: '', label: 'Any', counted: false, group: '', def: true });
steps.slice(kind === 'min' ? 0 : 1, kind === 'min' ? -1 : undefined).forEach(function (n) {
add(n + unit, stepLabel(n, unit), false);
master.push({ value: n + unit, label: stepLabel(n, unit), counted: true, group: '', def: false });
});
if (kind === 'max') add('', 'Any', !wasKm);
if (wasKm) select.value = nearestStep(select, wasKm);
if (kind === 'max') master.push({ value: '', label: 'Any', counted: false, group: '', def: true });
masters[kind] = master;
/* Every step is written once, so the nearest can be found; counting then takes out the empty ones. */
select.removeAttribute('data-sig');
renderSelect(select, function () { return 1; });
select.value = wasKm ? nearestStep(select, wasKm) : '';
});
}
function lengthSteps() {
/* Shortest and Longest offer the same steps: each is listed once, or it is counted twice. */
var out = [], seen = {};
['min', 'max'].forEach(function (k) {
masters[k].forEach(function (o) {
if (o.value && !seen[o.value]) { seen[o.value] = true; out.push([o.value, stepKm(o.value)]); }
});
});
return out;
}
function describeLength(s) {
var text;
if (!s.min && s.max === Infinity) text = 'Any length.';
@@ -1657,7 +1778,6 @@
function relabelLengths() {
buildLengthOptions();
setText(lenHint, describeLength(read()));
apply(true);
}
@@ -1671,30 +1791,45 @@
if (s.month) p.set('month', s.month);
if (s.kind) p.set('kind', s.kind);
MULTI.forEach(function (name) { if (s[name].length) p.set(name, s[name].join(',')); });
if (sort.value !== defaultSort) p.set('sort', sort.value);
if (sort && sort.value !== defaultSort) p.set('sort', sort.value);
return p.toString();
}
/* Before reading the address, every choice the page has is offered, so that one the address
names is found even when the last counting took it out. */
function offerAll() {
['where', 'month', 'min', 'max'].forEach(function (name) {
if (!el[name] || !el[name].tagName) return;
el[name].removeAttribute('data-sig');
renderSelect(el[name], function () { return 1; });
});
}
function fromQuery() {
var p = new URLSearchParams(window.location.search);
offerAll();
/* Left alone when it already says the same, so a space being typed stays. */
if (el.q.value.trim() !== (p.get('q') || '').trim()) el.q.value = p.get('q') || '';
var where = p.get('where') || p.get('region') || '';
if (!where && (p.get('country') === 'US' || p.get('country') === 'CA')) where = p.get('country');
el.where.value = hasOption(el.where, where) ? where : '';
if (el.where) {
var where = p.get('where') || p.get('region') || '';
if (!where && (p.get('country') === 'US' || p.get('country') === 'CA')) where = p.get('country');
el.where.value = hasOption(el.where, where) ? where : '';
}
/* A length in the address may be a step from the other unit's list (a link
from a reader who uses kilometres, opened by one who uses miles), or a
step this list no longer has: take the nearest step offered. */
['min', 'max'].forEach(function (name) {
var v = p.get(name) || '';
el[name].value = hasOption(el[name], v) ? v : nearestStep(el[name], stepKm(v));
});
/* An address that gives them the wrong way round is rewritten by apply()
with the shorter one first: the controls say the same. */
if (stepKm(el.min.value) > stepKm(el.max.value) && stepKm(el.max.value)) {
var low = el.max.value, high = el.min.value;
el.min.value = hasOption(el.min, low) ? low : nearestStep(el.min, stepKm(low));
el.max.value = hasOption(el.max, high) ? high : nearestStep(el.max, stepKm(high));
if (el.min && el.max) {
['min', 'max'].forEach(function (name) {
var v = p.get(name) || '';
el[name].value = hasOption(el[name], v) ? v : nearestStep(el[name], stepKm(v));
});
/* An address that gives them the wrong way round is rewritten by apply()
with the shorter one first: the controls say the same. */
if (stepKm(el.min.value) > stepKm(el.max.value) && stepKm(el.max.value)) {
var low = el.max.value, high = el.min.value;
el.min.value = hasOption(el.min, low) ? low : nearestStep(el.min, stepKm(low));
el.max.value = hasOption(el.max, high) ? high : nearestStep(el.max, stepKm(high));
}
}
if (el.month) {
var month = p.get('month') || '';
@@ -1703,38 +1838,105 @@
var kind = p.get('kind') || '';
if (kind === 'designated') kind = 'trail';
syncRadios('#finder-form input[name="kind"]', kind === 'trail' || kind === 'route' ? kind : '');
var lists = {};
MULTI.forEach(function (name) { lists[name] = (p.get(name) || '').split(',').filter(Boolean); });
if (p.get('line') === '1' && !lists.gpx.length) lists.gpx = ['here', 'partial'];
if (p.get('policy') && OLD_POLICY[p.get('policy')] && !lists.gpx.length) lists.gpx = [OLD_POLICY[p.get('policy')]];
var chosen = {};
MULTI.forEach(function (name) { chosen[name] = (p.get(name) || '').split(',').filter(Boolean); });
if (p.get('line') === '1' && !chosen.gpx.length) chosen.gpx = ['here', 'partial'];
if (p.get('policy') && OLD_POLICY[p.get('policy')] && !chosen.gpx.length) chosen.gpx = [OLD_POLICY[p.get('policy')]];
MULTI.forEach(function (name) {
boxes(name).forEach(function (b) { b.checked = lists[name].indexOf(b.value) !== -1; });
boxes(name).forEach(function (b) { b.checked = chosen[name].indexOf(b.value) !== -1; });
});
sort.value = normalizeSortKey(p.get('sort'), defaultSort);
if (sort) sort.value = normalizeSortKey(p.get('sort'), defaultSort);
}
function applySort() {
if (resultsRoot) applySortUI(resultsRoot, sort.value, false);
if (sort) applySortUI(resultsRoot, sort.value, false);
}
/* Is something chosen in the facet? */
function isSet(f, s) {
if (f === 'length') return !!s.min || s.max !== Infinity;
if (MULTI.indexOf(f) !== -1) return s[f].length > 0;
return !!s[f];
}
/* [[kind, value]] of every choice a field offers: kind is the facet, or min / max for length. */
function choicesOf(f) {
var out = [];
function from(list, k) { list.forEach(function (o) { if (o.value) out.push([k, o.value]); }); }
if (f === 'length') { from(masters.min, 'min'); from(masters.max, 'max'); }
else if (f === 'where' || f === 'month') from(masters[f], f);
else if (f === 'kind') { out.push([f, 'trail']); out.push([f, 'route']); }
else boxes(f).forEach(function (b) { out.push([f, b.value]); });
return out;
}
/* The numbers beside the choices, the choices that would show nothing taken out, and a
filter that can no longer narrow what the others leave put away with its heading. */
function relabel(s, c) {
renderSelect(el.where, function (v) { return v ? c.where[v] : c.base.where; });
renderSelect(el.month, function (v) { return c.month[v]; });
if (el.min && el.min.tagName) renderSelect(el.min, function (v) { return c.min[v]; });
if (el.max && el.max.tagName) renderSelect(el.max, function (v) { return c.max[v]; });
MULTI.forEach(function (name) {
boxes(name).forEach(function (b) {
var n = c[name][b.value] || 0;
var label = b.closest('label');
setText(label.querySelector('.check__count'), fmt.format(n));
label.hidden = n === 0 && !b.checked;
});
});
form.querySelectorAll('input[name="kind"]').forEach(function (b) {
var span = b.nextElementSibling;
if (!b.value || !span || !span.dataset.label) return;
var n = c.kind[b.value] || 0;
setText(span, span.dataset.label + ' (' + fmt.format(n) + ')');
b.closest('label').hidden = n === 0 && !b.checked;
});
var shown = 0;
fields.forEach(function (field) {
var f = field.dataset.facet;
var base = c.base[f];
/* Only the choices the field offers count: a row's other places (a trail that crosses
out of the page's part of the country) are not choices here. */
var counts = f === 'length' ? null : c[f];
var narrows = choicesOf(f).some(function (pair) {
var n = pair[0] === 'min' ? c.min[pair[1]] : pair[0] === 'max' ? c.max[pair[1]] : counts[pair[1]];
return n > 0 && n < base;
});
field.hidden = !narrows && !isSet(f, s);
if (!field.hidden) shown += 1;
});
if (more) more.hidden = !Array.prototype.some.call(more.querySelectorAll('[data-facet]'), function (f) { return !f.hidden; });
if (none) none.hidden = shown > 0;
}
function apply(updateUrl) {
var s = read();
var c = FacetCount.count(rows, s, lengthSteps());
var shown = [];
items.forEach(function (li) {
var ok = matches(li, s);
li.hidden = !ok;
if (ok) shown.push(li.dataset.id);
rows.forEach(function (d) {
var ok = FacetCount.passes(d, s, '');
d.li.hidden = !ok;
if (ok) shown.push(d.id);
});
var noun = total === 1 ? ' trail' : ' trails';
if (count && count.textContent !== shown.length + ' of ' + total + noun) {
/* A heading over rows (Routes, by author) goes when none of its rows is left. */
lists.forEach(function (ol) {
var head = ol.previousElementSibling;
var any = !!ol.querySelector('.entry:not([hidden])');
ol.hidden = !any;
if (head && head.classList.contains('results__group')) head.hidden = !any;
});
var text = shown.length + ' of ' + total + ' ' + noun;
if (count && count.textContent !== text) {
count.innerHTML = '';
var strong = document.createElement('strong');
strong.textContent = String(shown.length);
count.appendChild(strong);
count.appendChild(document.createTextNode(' of ' + total + noun));
count.appendChild(document.createTextNode(' of ' + total + ' ' + noun));
}
empty.hidden = shown.length > 0;
if (empty) empty.hidden = shown.length > 0;
if (listHead) listHead.hidden = shown.length === 0;
relabel(s, c);
setText(lenHint, describeLength(s));
/* Say how many trails a filter leaves out for having no value on file. */
@@ -1742,7 +1944,7 @@
form.querySelectorAll('[data-missing]').forEach(function (note) { note.hidden = !on[note.dataset.missing]; });
var n = MORE.reduce(function (sum, name) { return sum + (s[name].length ? 1 : 0); }, 0);
active.textContent = n ? n + ' on' : '';
if (active) active.textContent = n ? n + ' on' : '';
var all = (s.where ? 1 : 0) + (s.min ? 1 : 0) + (s.max !== Infinity ? 1 : 0) + (s.month ? 1 : 0) + (s.kind ? 1 : 0) +
(s.time.length ? 1 : 0) + (s.terrain.length ? 1 : 0) + n;
setText(form.querySelector('.filters__count'), all ? String(all) : '');
@@ -1760,16 +1962,17 @@
form.addEventListener('change', function () { apply(true); });
form.addEventListener('submit', function (e) { e.preventDefault(); });
form.addEventListener('reset', function () { setTimeout(function () { apply(true); }, 0); });
document.querySelectorAll('[data-reset]').forEach(function (b) {
resultsRoot.querySelectorAll('[data-reset]').forEach(function (b) {
b.addEventListener('click', function () { form.reset(); el.q.focus(); });
});
sort.addEventListener('change', function () { applySort(); apply(true); announceSort(resultsRoot, sort.value); });
if (resultsRoot) wireSortHeads(resultsRoot, function () { return sort.value; }, function (k) {
if (sort) sort.addEventListener('change', function () { applySort(); apply(true); announceSort(resultsRoot, sort.value); });
if (sort) wireSortHeads(resultsRoot, function () { return sort.value; }, function (k) {
sort.value = k; applySort(); apply(true); announceSort(resultsRoot, sort.value);
});
document.addEventListener('olt:units', relabelLengths);
items.forEach(function (li) {
rows.forEach(function (d) {
var li = d.li;
li.addEventListener('mouseenter', function () { highlight(li.dataset.id); });
li.addEventListener('mouseleave', function () { highlight(''); });
li.addEventListener('focusin', function () { highlight(li.dataset.id); });
@@ -1787,9 +1990,9 @@
/* The filters behind "More" stay folded, unless the address already sets one. */
var s0 = read();
if (more && MORE.some(function (name) { return s0[name].length; })) more.open = true;
/* The panels open from the bar; they start open when the address already sets a filter. */
var firstOn = s0.where || s0.min || s0.max !== Infinity || s0.month || s0.kind || s0.time.length || s0.terrain.length;
if (firstOn || MORE.some(function (name) { return s0[name].length; })) showPanels(true);
/* The panels start closed on every page, whatever the address sets (the Filters control
says how many are on). An address ending #filters opens them: a link can offer them. */
if (window.location.hash === '#filters') showPanels(true);
window.addEventListener('popstate', function () { fromQuery(); applySort(); apply(false); });
/* A page reached by Back, Forward or a reload: the browser may put the old
values of the controls back after this script has run, or show an old copy
+39 -29
View File
@@ -989,7 +989,7 @@ html.js .map__status:not([data-say]) { display: none; }
.home { padding-block: var(--space-4) var(--space-7); }
.finder__notes { display: grid; gap: var(--space-2); margin-block-start: var(--space-6); }
.results { container: results / inline-size; }
.home__bar { margin-block-end: var(--space-3); }
.finder__bar { margin-block-end: var(--space-3); }
/* Every page that shows a set of trails: the rows, with their map. Wide: the rows on the left, the
map on the right, where it stays in view as the rows scroll. Narrow: the map is a short band above
@@ -1022,7 +1022,7 @@ html.js .map__status:not([data-say]) { display: none; }
}
@media (min-width: 56rem) and (pointer: fine) {
.browse .results-sort .select { min-block-size: 2.25rem; }
.home .filters__bar .input, .home .filters__bar .button { min-block-size: 2.5rem; }
.browse .filters__bar .input, .browse .filters__bar .button { min-block-size: 2.5rem; }
}
.browse--no-map .note { margin-block-start: var(--space-5); max-inline-size: var(--measure); color: var(--ink-2); font: 400 var(--step--1)/1.5 var(--font-sans); }
.browse-about { margin-block-start: var(--space-7); padding-block-start: var(--space-4); border-block-start: 1px solid var(--ink); }
@@ -1040,34 +1040,28 @@ html.js .map__status:not([data-say]) { display: none; }
.filters__toggle[aria-expanded="true"] { background: var(--ink); border-color: var(--ink); color: var(--paper); }
.filters__toggle .filters__count:not(:empty) { background: var(--paper); color: var(--ink); }
.filters__clear[hidden] { display: none; }
/* The panels: the existing filter fields, in columns where there is room. With JavaScript they
open from the bar; without it the bar and panels are not offered at all (see below). */
.filters { position: relative; }
/* The panels: the filter fields, in columns where there is room. With JavaScript they open from
the bar; without it the bar and panels are not offered at all (see below). Open, they sit in the
page between the bar and the rows, and the rows move down: nothing is drawn over a row, and the
map beside them shows what the filters leave. */
.filters__panels { margin-block-start: var(--space-2); border: 1px solid var(--ink); background: var(--surface); }
html.js .filters__panels:not([data-open]) { display: none; }
/* Open, the panels lie over the rows below the bar, as a sheet laid on the table: the page does not
move, and the map beside them shows what the filters leave. */
html.js .filters__panels {
position: absolute;
z-index: 30;
inset-inline: 0;
inset-block-start: 100%;
max-block-size: min(72svh, 46rem);
overflow-y: auto;
overscroll-behavior: contain;
box-shadow: 6px 6px 0 var(--rule);
}
.filters__end { position: sticky; inset-block-end: 0; display: flex; justify-content: flex-end; padding: var(--space-3) var(--space-4); border-block-start: 1px solid var(--rule); background: var(--surface); }
/* A choice or a filter that would show nothing is put away by app.js with [hidden]; the fields'
own display must not bring it back. */
.filters [hidden] { display: none !important; }
.filters__end .button { min-block-size: 2.5rem; }
.filters__none { padding: var(--space-3) var(--space-4) 0; color: var(--ink-2); font: 400 var(--step--1)/1.4 var(--font-sans); }
.filters__end { position: sticky; inset-block-end: 0; display: flex; justify-content: flex-end; padding: var(--space-2) var(--space-4); border-block-start: 1px solid var(--rule); background: var(--surface); }
.filters__panel > summary { display: none; }
.filters__more { border-block-start: 1px solid var(--rule); }
.filters__more > summary {
display: flex;
align-items: center;
gap: var(--space-3);
padding: var(--space-2) var(--space-4);
min-block-size: 2.75rem;
background: var(--ink);
color: var(--paper);
font: 600 var(--step--1)/1.3 var(--font-sans);
padding: var(--space-1) var(--space-4);
min-block-size: 2.5rem;
color: var(--ink);
font: 600 var(--step--2)/1.3 var(--font-sans);
letter-spacing: 0.08em;
text-transform: uppercase;
cursor: pointer;
@@ -1084,23 +1078,33 @@ html.js .filters__panels {
transform: translateY(-25%) rotate(45deg);
}
.filters__more[open] > summary::after { transform: translateY(25%) rotate(-135deg); }
.filters__more > summary:focus-visible { outline-offset: -5px; outline-color: var(--paper); }
.filters__more > summary:hover { background: var(--sunken); }
.filters__more > summary:focus-visible { outline-offset: -3px; }
.filters__active:not(:empty) {
padding: 0 var(--space-2);
border-radius: 999px;
background: var(--paper);
color: var(--ink);
background: var(--ink);
color: var(--paper);
font-weight: 600;
letter-spacing: 0.02em;
text-transform: none;
}
/* The fields run in as many columns as the panel has room for. */
/* The fields run in as many columns as the panel has room for; a field of choices laid out as
pills (Time, Terrain) takes the whole width, so its pills run across in a line or two rather
than down one column. Kept tight, so that the first rows are still in view under the open panel
where the window allows. */
.filters__first, .filters__form {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(min(100%, 15rem), 1fr));
gap: var(--space-4) var(--space-5);
padding: var(--space-4);
gap: var(--space-3) var(--space-5);
padding: var(--space-3) var(--space-4);
}
.filters__first > .field--wide { grid-column: 1 / -1; }
.filters .field { gap: var(--space-1); }
.filters .field legend { margin-block-end: var(--space-1); }
.filters .pills { gap: var(--space-1) var(--space-2); }
.filters .pills .check__text { font-size: var(--step--1); }
.filters .field__hint { font-size: var(--step--2); }
.field { display: grid; align-content: start; gap: var(--space-2); min-inline-size: 0; margin: 0; padding: 0; border: 0; }
.field__label, .field legend {
@@ -1177,6 +1181,12 @@ html.js .filters__panels {
.results-tools { flex-basis: 100%; }
.results-sort { flex: 1 1 100%; }
.results-sort .select { flex: 1 1 auto; }
/* Under a filter bar the count and the sort share one line: the bar costs little height. */
.results[data-finder] .results-head { flex-wrap: nowrap; align-items: center; }
.results[data-finder] .results-tools { flex: 0 1 auto; flex-basis: auto; }
.results[data-finder] .results-sort { flex: 0 1 auto; }
.results[data-finder] .results-sort__label { position: absolute; inline-size: 1px; block-size: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
.results[data-finder] .results-count { flex: none; }
}
.key {
display: flex;
+115 -59
View File
@@ -226,6 +226,15 @@ def entry(rec, *, level=3, extra="", routes_list=False, hidden=False, eager=Fals
# The filters ------------------------------------------------------------------
# One bar and one set of panels, on the home page and on every other page that shows a set of at
# least FILTER_MIN trails (listing()). Everything is built from the page's own trails: a facet that
# cannot narrow them is left out, and an option none of them has is not written. The numbers written
# here are for the whole set; app.js counts again from the rows on the page every time anything
# changes, and hides an option that would show nothing (its counting is facetCounts(), which
# web/tests/test_filter_counts.py runs under node against counts made here from the records).
FILTER_MIN = 10
def _length_options(steps, selected_any_last, unit="mi"):
opts = [f'<option value="{step_value(n, unit)}">{step_label(n, unit)}</option>' for n in steps]
@@ -234,26 +243,48 @@ def _length_options(steps, selected_any_last, unit="mi"):
return '<option value="">Any</option>' + "".join(opts[:-1])
def where_options(c):
"""The Where filter: the two countries, then each place group with its states and provinces."""
opts = [f'<option value="">Anywhere ({c["total"]})</option>']
def _opt(value, label, n):
"""A counted option: its name in data-label, for app.js to write each new count after it."""
return f'<option value="{esc(value)}" data-label="{esc(label)}">{esc(label)} ({n})</option>'
def where_options(c, scope="all"):
"""The Where filter. scope "all": the two countries, then each place group with its states and
provinces. scope "g:<group>": the page of one group: all of it first (the page's whole set),
then only the places inside it. An option that would show every trail of the page is the same as
the first one, and one that would show none is not written."""
total = c["total"]
def useful(key):
return 0 < c["where:" + key] < total
if scope.startswith("g:"):
g = scope[2:]
keys = next(k for x, _, k in facets.PLACE_GROUPS if x == g)
opts = [_opt("", f"All of {facets.GROUP_NAME[g]}", total)]
opts += [_opt(k, facets.place_name(k), c["where:" + k]) for k in sorted(keys, key=facets.place_name) if useful(k)]
if g in {facets.GROUP_OF[k] for k in facets.GROUP_OF if k.startswith("CA-")} and useful(facets.ACROSS_CANADA):
opts.append(_opt(facets.ACROSS_CANADA, facets.ACROSS_CANADA_NAME, c["where:" + facets.ACROSS_CANADA]))
return "".join(opts)
opts = [_opt("", "Anywhere", total)]
for code in ("US", "CA"):
if c["where:" + code]:
opts.append(f'<option value="{code}">{esc(words.COUNTRIES[code])} ({c["where:" + code]})</option>')
if useful(code):
opts.append(_opt(code, words.COUNTRIES[code], c["where:" + code]))
for g, name, keys in facets.PLACE_GROUPS:
if not c["where:g:" + g]:
continue
inner = [f'<option value="g:{g}">All of {esc(name)} ({c["where:g:" + g]})</option>']
for key in sorted(keys, key=facets.place_name):
if c["where:" + key]:
inner.append(f'<option value="{key}">{esc(facets.place_name(key))} ({c["where:" + key]})</option>')
opts.append(f'<optgroup label="{esc(name)}">{"".join(inner)}</optgroup>')
if c["where:" + facets.ACROSS_CANADA]:
opts.append(f'<option value="{facets.ACROSS_CANADA}">{facets.ACROSS_CANADA_NAME} '
f'({c["where:" + facets.ACROSS_CANADA]})</option>')
inner = [_opt("g:" + g, f"All of {name}", c["where:g:" + g])] if useful("g:" + g) else []
inner += [_opt(k, facets.place_name(k), c["where:" + k]) for k in sorted(keys, key=facets.place_name) if useful(k)]
if inner:
opts.append(f'<optgroup label="{esc(name)}">{"".join(inner)}</optgroup>')
if useful(facets.ACROSS_CANADA):
opts.append(_opt(facets.ACROSS_CANADA, facets.ACROSS_CANADA_NAME, c["where:" + facets.ACROSS_CANADA]))
return "".join(opts)
def _narrows(c, prefix, values):
"""True when choosing some value of the facet would show some of the trails but not all."""
return any(0 < c[f"{prefix}:{v}"] < c["total"] for v in values)
def _checks(name, items, c, prefix, hints=None):
"""Checkboxes for a multi-choice facet: (value, label) items with their counts."""
out = []
@@ -277,17 +308,25 @@ def _missing(records, key):
f'{esc(facets.missing_text(without, key))} They are left out while this filter is on.</p>')
def finder_form(records, c=None, steps=None):
"""Search and the first-rank filters in view; Walking, Shape and GPX behind "More"."""
def finder_form(records, c=None, steps=None, where="all"):
"""The bar (search, Filters, Clear) and the panels: the first-rank filters, then Walking, Shape and
GPX behind "More". records: the page's own trails. where: the Where filter's scope ("all",
"g:<group>" on a group's page, "" for none: a state's page). A facet is written only when it can
narrow these trails; each field carries data-facet, for app.js to hide it when it no longer can."""
c = c or counts(records)
steps = steps or length_steps(records)
km_steps = length_steps(records, "km")
first, more = [], []
first.append(f"""<div class="field">
if where:
opts = where_options(c, where)
if opts.count("<option") > 1:
first.append(f"""<div class="field" data-facet="where">
<label class="field__label" for="where">{facets.WHERE}</label>
<select class="select" id="where" name="where">{where_options(c)}</select>
<select class="select" id="where" name="where">{opts}</select>
</div>""")
first.append(f"""<fieldset class="field">
kms = [r["length_km"] for r in records]
if any(min(kms) < n * words.KM_PER_MI <= max(kms) for n in steps):
first.append(f"""<fieldset class="field" data-facet="length">
<legend>{facets.LENGTH}</legend>
<div class="range">
<label class="vh" for="min">Shortest length</label>
@@ -298,51 +337,60 @@ def finder_form(records, c=None, steps=None):
</div>
<p class="field__hint" id="len-hint" aria-live="polite">Any length.</p>
</fieldset>""")
first.append(f"""<fieldset class="field">
if _narrows(c, "time", [k for k, _, _ in facets.TIME_BANDS]):
first.append(f"""<fieldset class="field field--wide" data-facet="time">
<legend>{facets.TIME}</legend>
<div class="pills">{_checks("time", [(k, label) for k, label, _ in facets.TIME_BANDS], c, "time")}</div>
<p class="field__hint">To walk it all. Where no source says, it is estimated from the length.</p>
</fieldset>""")
if facets.offered(records, "season"):
month_opts = "".join(f'<option value="{i}">{esc(m)} ({c[f"month:{i}"]})</option>'
for i, m in enumerate(facets.MONTHS, 1))
first.append(f"""<div class="field">
if facets.offered(records, "season") and _narrows(c, "month", range(1, 13)):
month_opts = "".join(_opt(str(i), m, c[f"month:{i}"]) for i, m in enumerate(facets.MONTHS, 1) if c[f"month:{i}"])
first.append(f"""<div class="field" data-facet="month">
<label class="field__label" for="month">{facets.SEASON}</label>
<select class="select" id="month" name="month"><option value="">Any month</option>{month_opts}</select>
<p class="field__hint">Trails usually walked in that month.</p>
{_missing(records, "season")}
</div>""")
if facets.offered(records, "terrain"):
first.append(f"""<fieldset class="field">
if _narrows(c, "kind", facets.KINDS):
first.append(f"""<fieldset class="field" data-facet="kind">
<legend>{facets.KIND}</legend>
<div class="seg">
<label><input type="radio" name="kind" value="" checked><span>Any</span></label>
<label><input type="radio" name="kind" value="trail"><span data-label="Official">Official ({c["kind:trail"]})</span></label>
<label><input type="radio" name="kind" value="route"><span data-label="Routes">Routes ({c["kind:route"]})</span></label>
</div>
<p class="field__hint"><a href="/routes/">What is a route?</a></p>
</fieldset>""")
if facets.offered(records, "terrain") and _narrows(c, "terrain", facets.TERRAIN_VALUES):
first.append(f"""<fieldset class="field field--wide" data-facet="terrain">
<legend>{facets.TERRAIN}</legend>
<div class="pills">{_checks("terrain", facets.TERRAIN_VALUES.items(), c, "terrain")}</div>
{_missing(records, "terrain")}
</fieldset>""")
first.append(f"""<fieldset class="field">
<legend>{facets.KIND}</legend>
<div class="seg">
<label><input type="radio" name="kind" value="" checked><span>Any</span></label>
<label><input type="radio" name="kind" value="trail"><span>Official ({c["kind:trail"]})</span></label>
<label><input type="radio" name="kind" value="route"><span>Routes ({c["kind:route"]})</span></label>
</div>
<p class="field__hint"><a href="/routes/">What is a route?</a></p>
</fieldset>""")
if facets.offered(records, "walking"):
more.append(f"""<fieldset class="field">
if facets.offered(records, "walking") and _narrows(c, "walking", facets.WALKING_VALUES):
more.append(f"""<fieldset class="field" data-facet="walking">
<legend>{facets.WALKING}</legend>
{_checks("walking", facets.WALKING_VALUES.items(), c, "walking", facets.WALKING_HINT)}
{_missing(records, "walking")}
</fieldset>""")
if facets.offered(records, "shape"):
more.append(f"""<fieldset class="field">
if facets.offered(records, "shape") and _narrows(c, "shape", facets.SHAPES):
more.append(f"""<fieldset class="field" data-facet="shape">
<legend>{facets.SHAPE}</legend>
{_checks("shape", facets.SHAPES.items(), c, "shape")}
{_missing(records, "shape")}
</fieldset>""")
more.append(f"""<fieldset class="field">
if _narrows(c, "gpx", facets.GPX_FILTER):
more.append(f"""<fieldset class="field" data-facet="gpx">
<legend>{facets.GPX}</legend>
{_checks("gpx", facets.GPX_FILTER.items(), c, "gpx")}
</fieldset>""")
more_html = f"""
<details class="filters__more">
<summary>More filters <span class="filters__active"></span></summary>
<div class="filters__form">
{"".join(more)}
</div>
</details>""" if more else ""
return f"""<form class="filters" id="finder-form" role="search" aria-label="Find a trail">
<div class="filters__bar">
<div class="filters__search field">
@@ -358,18 +406,24 @@ def finder_form(records, c=None, steps=None):
<div class="filters__first">
{"".join(first)}
</div>
</details>
<details class="filters__more">
<summary>More filters <span class="filters__active"></span></summary>
<div class="filters__form">
{"".join(more)}
</div>
</details>
</details>{more_html}
<p class="filters__none" hidden>Nothing here narrows these trails further.</p>
<p class="filters__end js-only"><button class="button filters__done" type="button">Show the trails</button></p>
</div>
</form>"""
def listing(recs=None, *, where="all", groups=None, **kw):
"""The rows of a page that shows a set of trails, with the filter bar over them when the set
has at least FILTER_MIN trails (else results() alone). where: the Where filter's scope
(finder_form). The other arguments are results()'s."""
trails = [r for g in groups for r in g[1]] if groups is not None else list(recs)
if len(trails) < FILTER_MIN:
return results(recs, groups=groups, **kw)
return Markup(f"""<div class="finder__bar">{finder_form(trails, where=where)}</div>
{results(recs, groups=groups, finder=True, **kw)}""")
# The list ---------------------------------------------------------------------
# The length strip's ticks (style.css .loglen): 100, 1,000 and 10,000 miles, or
@@ -463,14 +517,15 @@ def key(official=True):
def results(recs=None, *, finder=False, groups=None, routes_list=False, default_sort="name", saved=False, top=3,
ranked="", lead=None, more=None, tools=True, by=None):
ranked="", lead=None, more=None, tools=True, by=None, every=False):
"""The list of trails, as every page shows it: div.results > head, key, list head, ol.entries.
Every list carries the same "Sort by" control. The rows are written in
default_sort order (a key of facets.SORTS), so the page is right with
JavaScript off; app.js reorders in place and keeps ?sort= in the address.
finder: the home page's list, driven by the filters (live count, empty state).
finder: a list driven by the filter bar over it (listing(): live count, empty state).
every: the list holds every trail (the home page's).
groups: [(heading, trails, extra_fn)] to list the trails under headings (level `top`);
sorting is within each group and the groups keep their order. A heading may be a pair
(heading HTML, intro HTML): the intro is a sentence under the heading (an author's summary).
@@ -483,7 +538,7 @@ def results(recs=None, *, finder=False, groups=None, routes_list=False, default_
app.js shows the saved ones (or a link's) and writes the count; the sort
control opens on the order saved.
A list that holds every trail (the finder's, the Saved page's) is marked
A list that holds every trail (the home page's, the Saved page's) is marked
data-every-trail: there app.js knows every trail id, and drops the saved
ids that match no trail.
@@ -503,7 +558,7 @@ def results(recs=None, *, finder=False, groups=None, routes_list=False, default_
only_routes = bool(shown) and all(facets.kind(r) == "route" for r in shown)
noun = ("route" if only_routes else "trail") + ("" if total == 1 else "s")
lists = ""
every = ' data-every-trail' if finder or saved else ""
every = ' data-every-trail' if every or saved else ""
seen = 0
for heading, items, extra_fn in groups:
level = top + 1 if heading else top
@@ -519,14 +574,14 @@ def results(recs=None, *, finder=False, groups=None, routes_list=False, default_
lists += f'\n <div class="results__lead"><h{top} class="results__group">{heading}</h{top}>{intro}</div>'
elif heading:
lists += f'\n <h{top} class="results__group">{heading}</h{top}>'
list_id = ' id="entries"' if finder else ""
list_id = ' id="entries"' if finder and len(groups) == 1 else ""
lists += f'\n <ol class="entries"{list_id}{every}>\n{rows}\n </ol>'
if finder:
count = (f'<p class="results-count" id="results-count" role="status">'
count = (f'<p class="results-count" id="results-count" role="status" data-noun="{noun}">'
f'<strong>{total}</strong> of {total} {noun}</p>')
empty = """
empty = f"""
<div class="empty-state" id="empty-state" hidden>
<p><strong>No trails match these filters.</strong></p>
<p><strong>No {noun} match these filters.</strong></p>
<button class="button button--quiet" type="button" data-reset>Clear search and filters</button>
</div>"""
elif saved:
@@ -539,7 +594,8 @@ def results(recs=None, *, finder=False, groups=None, routes_list=False, default_
return Markup(f'<div class="results results--short">{lists}</div>')
tools = sort_select(default_sort, saved=saved, ranked=ranked)
dflt = SAVED_ORDER[0] if saved else "rank" if ranked else default_sort
return Markup(f"""<div class="results" data-sortable data-default-sort="{esc(dflt)}">
finder_attr = " data-finder" if finder else ""
return Markup(f"""<div class="results"{finder_attr} data-sortable data-default-sort="{esc(dflt)}">
<div class="results-head">
{count}
<div class="results-tools">
@@ -743,8 +799,8 @@ def render(records, site, repo_root=""):
f'<a href="{esc(site.correction_url())}">Report a problem</a> or '
f'<a href="{esc(site.new_trail_url)}">suggest a trail</a>.</p>')
picks = home_picks(datafiles.lists(repo_root))
listing = f"""<div class="home__bar">{finder_form(records, c, length_steps(records))}</div>
{results(recs, finder=True)}"""
listing = f"""<div class="finder__bar">{finder_form(records, c, length_steps(records))}</div>
{results(recs, finder=True, every=True)}"""
return f"""<section class="intro" aria-labelledby="intro-title">
<div class="container intro__inner">
<h1 id="intro-title">{esc(site.tagline.rstrip("."))}</h1>
+8
View File
@@ -144,6 +144,14 @@ def render_site(records, out_dir, repo_root, site=None):
path = f"/regions/{slug}/"
region_paths.append(path)
add(path, t, d, b, maps=needs_map, recs=by_slug[slug]["records"])
# The parts of the country (facets.PLACE_GROUPS), each a page of its own.
for g, _, _ in facets.PLACE_GROUPS:
built = regions.group_page(g, records, site)
if built:
t, d, b, needs_map, recs = built
path = regions.group_path(g)
region_paths.append(path)
add(path, t, d, b, maps=needs_map, recs=recs)
# Pages for one kind of trail in one place (olt/placefacets.py).
for p in facet_plan:
t, d, b, needs_map = placefacets.page(p, records, site, facet_plan)
+1 -1
View File
@@ -105,7 +105,7 @@ def page(p, records, site, all_pages):
</div></header>
</div></div>
<div class="container section place">
{home.browse_view(home.results(recs, default_sort=lst.sort, top=2), home.overview_map(recs, f"Map of the trails in {name}: {lst.title}"),
{home.browse_view(home.listing(recs, default_sort=lst.sort, top=2, where=""), home.overview_map(recs, f"Map of the trails in {name}: {lst.title}"),
about=summary.facts(recs, records), about_title=f"About these trails in {name}")}
<nav class="region-nav" aria-label="Lists"><a href="{esc(browse.path(lst))}">{esc(lst.title)} everywhere</a> · <a href="/lists/">All lists</a></nav>
{nav}
+59 -10
View File
@@ -89,9 +89,9 @@ def regions_index_page(records, site):
f'<span class="places__n">{_plural(len(i["records"]))}</span></li>'
for i in infos)
blocks += f"""<section class="places__group" aria-labelledby="{esc(g)}">
<h2 id="{esc(g)}">{esc(name)}</h2>
<h2 id="{esc(g)}"><a href="{esc(group_path(g))}">{esc(name)}</a></h2>
<p class="places__sum">{_plural(len(recs))}, {_gpx_count(recs)} with a GPX here.
<a href="/?where=g:{esc(g)}">See them with the filters</a></p>
<a href="{esc(group_path(g))}">All {_plural(len(recs))} in {esc(name)}</a></p>
<ul class="places__list">{rows}</ul>
</section>"""
if across:
@@ -116,6 +116,57 @@ def regions_index_page(records, site):
return "Long Trails by State and Province: US and Canada", common.cut_at_word(description, common.DESCRIPTION_LIMIT), Markup(body)
def group_path(g):
"""The page of a part of the country: /regions/<group key>/ (state and province pages are
/regions/<us-xx or ca-xx>/, so the two never meet)."""
return f"/regions/{g}/"
def group_page(g, records, site):
"""(title, description, body, needs_map, recs) for /regions/<group>/: the trails in one part of
the country (facets.PLACE_GROUPS), or None when no trail is there. A trail that crosses all of
Canada is in every Canadian part, as the home page's Where filter counts it."""
recs = sorted(group_records(records, g), key=home.sort_name)
if not recs:
return None
name = facets.GROUP_NAME[g]
by_slug, _ = collect_regions(records)
keys = next(k for x, _, k in facets.PLACE_GROUPS if x == g)
places = sorted((by_slug[k.lower()] for k in keys if k.lower() in by_slug), key=lambda i: i["name"])
countries = {i["country"] for i in places}
country = words.COUNTRIES[next(iter(countries))] if len(countries) == 1 else ""
n_gpx = _gpx_count(recs)
states = words.join_names(esc(i["name"]) for i in places)
lede = f"{_plural(len(recs))} in {states}, {n_gpx} with a GPX here."
nav = (f'<nav class="region-nav" aria-label="Places in {esc(name)}">Places in {esc(name)}, and how many there: '
+ " · ".join(f'<a href="{esc(facets.place_path(i["key"]))}">{esc(i["name"])}</a> ({len(i["records"])})'
for i in places) + "</nav>")
others = [(x, n) for x, n, _ in facets.PLACE_GROUPS if x != g and group_records(records, x)]
nav += (f'<nav class="region-nav" aria-label="Other parts">Other parts: '
+ " · ".join(f'<a href="{esc(group_path(x))}">{esc(n)}</a>' for x, n in others) + "</nav>")
body = f"""<div class="page-head"><div class="container">
<nav class="breadcrumb" aria-label="Breadcrumb"><ol><li><a href="/regions/">Places</a></li><li aria-current="page">{esc(name)}</li></ol></nav>
<header class="titleblock"><div class="titleblock__text">
<p class="kicker">{esc(country or "United States and Canada")}</p>
<h1>{esc(name)}</h1>
<p class="page-head__lede">{lede}</p>
</div></header>
</div></div>
<div class="container section place">
{home.browse_view(home.listing(recs, top=2, where="g:" + g), home.overview_map(recs, f"Map of the trails in {name}"),
about=f"{summary.facts(recs, records)}{summary.details(recs)}", about_title=f"About the trails in {name}")}
{nav}
</div>"""
title = common.fit_title([f"Long Trails in {name}: {_plural(len(recs), 'Trail')}", f"Long Trails in {name}"], site)
by_length = sorted(recs, key=lambda r: (r["length_km"], r["id"]))
first = (f"{_plural(len(recs))} in {name} ({words.join_names(i['name'] for i in places)}), from "
f"{common.plain_name(by_length[0])}, {_miles(by_length[0])} miles, to {common.plain_name(by_length[-1])}, "
f"{_miles(by_length[-1])} miles.")
gpx = f" {_with_gpx(n_gpx, len(recs))[:1].upper()}{_with_gpx(n_gpx, len(recs))[1:]}." if n_gpx else ""
desc = _fit([first + gpx, first, f"{_plural(len(recs))} in {name}.{gpx}"])
return title, desc, Markup(body), home.has_overview_map(recs), recs
def region_page(slug, records, site, facet_pages=()):
"""(title, description, body, needs_map) for /regions/<slug>/: the trails in one state or province.
@@ -130,7 +181,7 @@ def region_page(slug, records, site, facet_pages=()):
n_gpx = _gpx_count(recs)
crumbs = '<li><a href="/regions/">Places</a></li>'
if group:
crumbs += f'<li><a href="/regions/#{esc(group)}">{esc(group_name)}</a></li>'
crumbs += f'<li><a href="{esc(group_path(group))}">{esc(group_name)}</a></li>'
siblings = []
if group:
_, _, keys = next(x for x in facets.PLACE_GROUPS if x[0] == group)
@@ -151,12 +202,11 @@ def region_page(slug, records, site, facet_pages=()):
<header class="titleblock"><div class="titleblock__text">
<p class="kicker">{esc(group_name + " · " if group_name else "")}{esc(country)}</p>
<h1>{esc(info["name"])}</h1>
<p class="page-head__lede">{_plural(len(recs))} in {esc(info["name"])}, {n_gpx} with a GPX here.
<a href="/?where={esc(key)}">Narrow them with the filters</a>.</p>
<p class="page-head__lede">{_plural(len(recs))} in {esc(info["name"])}, {n_gpx} with a GPX here.</p>
</div></header>
</div></div>
<div class="container section place">
{home.browse_view(home.results(recs, top=2), home.overview_map(recs, f"Map of the trails in {info['name']}"),
{home.browse_view(home.listing(recs, top=2, where=""), home.overview_map(recs, f"Map of the trails in {info['name']}"),
about=f"{summary.facts(recs, records)}{summary.details(recs)}",
about_title=f"About the trails in {info['name']}")}
{nav}
@@ -219,8 +269,7 @@ def routes_page(records, site, repo_root=None, after="", author_pages=None, n_au
how rough it is: some routes are on maintained trail all the way, and some official trails have
long road walks. The Walking line on each trail&rsquo;s page says what the walking is.</p>
<p>{_plural(len(routes), "route")}, by {n_authors_said} authors. {n_gpx} {"has" if n_gpx == 1 else "have"} a GPX here; for the rest,
each route&rsquo;s page says whether its author gives the track away, sells it, or does not publish it.
<a href="/?kind=route">Narrow them with the filters</a>.</p>"""
each route&rsquo;s page says whether its author gives the track away, sells it, or does not publish it.</p>"""
head_count = (f'\n <p class="page-head__lede">{_plural(len(routes), "route")} by <a href="/authors/">{_plural(n_authors, "author")}</a></p>'
if n_authors else "")
body = f"""<div class="page-head"><div class="container">
@@ -230,7 +279,7 @@ def routes_page(records, site, repo_root=None, after="", author_pages=None, n_au
<p class="page-head__lede" id="what-is-a-route">{esc(facets.ROUTE_DEFINITION)}</p>{head_count}
</div></header></div></div>
<div class="container section place">
{home.browse_view(home.results(groups=groups, routes_list=True, top=2), home.overview_map(routes, "Map of the routes with a GPX here"),
{home.browse_view(home.listing(groups=groups, routes_list=True, top=2), home.overview_map(routes, "Map of the routes with a GPX here"),
about=intro, about_title="About routes")}
{after}
<nav class="region-nav" aria-label="Other lists">{'<a href="/authors/">Route authors</a> · ' if linked else ""}<a href="/lists/">All lists</a> · <a href="/">Every trail</a></nav>
@@ -264,7 +313,7 @@ def list_page(lst, recs, total, site, *, records=None, before="", after="", lead
</div></header>
</div></div>
<div class="container section place">
{home.browse_view(home.results(recs, default_sort=lst.sort, top=2, lead=lead),
{home.browse_view(home.listing(recs, default_sort=lst.sort, top=2, lead=lead),
home.overview_map(recs, f"Map of the trails in the list {lst.title}"),
about=f"{about}{before}{f'<p>{esc(note.strip())}</p>' if note else ''}<p class=\"finder__foot\">{rule}</p>",
about_title="About this list")}
+23 -3
View File
@@ -166,7 +166,7 @@ class ExtraPagesTest(unittest.TestCase):
home_doc = read_out("index.html")
by_slug, across = regions_mod.collect_regions(self.records)
# each state or province option's count is the number of trails on its place page
found = re.findall(r'<option value="((?:US|CA)-[A-Z]{2})">[^<(]+\((\d+)\)</option>', home_doc)
found = re.findall(r'<option value="((?:US|CA)-[A-Z]{2})" data-label="[^"]*">[^<(]+\((\d+)\)</option>', home_doc)
self.assertEqual({v for v, _ in found}, {i["key"] for i in by_slug.values()})
for value, n in found:
page = read_out(f"regions/{value.lower()}/index.html")
@@ -174,10 +174,10 @@ class ExtraPagesTest(unittest.TestCase):
# and the rows that say they are there
self.assertEqual(int(n), len(re.findall(rf'data-where="[^"]*\b{value}\b', home_doc)), value)
for country, label in (("US", "United States"), ("CA", "Canada")):
n = int(re.search(rf'<option value="{country}">{label} \((\d+)\)</option>', home_doc).group(1))
n = int(re.search(rf'<option value="{country}" data-label="{label}">{label} \((\d+)\)</option>', home_doc).group(1))
self.assertEqual(n, sum(1 for r in self.records if country in common.countries(r)), country)
for g, name, _ in facets.PLACE_GROUPS:
m = re.search(rf'<option value="g:{g}">All of {re.escape(name)} \((\d+)\)</option>', home_doc)
m = re.search(rf'<option value="g:{g}" data-label="All of {re.escape(name)}">All of {re.escape(name)} \((\d+)\)</option>', home_doc)
n = sum(1 for r in self.records if g in facets.place_groups(r))
self.assertEqual(int(m.group(1)) if m else 0, n, g)
# No trail spans a whole country now that the Trans Canada Trail is gone;
@@ -433,5 +433,25 @@ class SeoTest(unittest.TestCase):
self.assertIn("Sitemap: https://example.org/sitemap.xml", f.read())
class NoFilterInstructionsTest(unittest.TestCase):
"""The pages that show a set of trails have the filter bar themselves: no page sends a visitor to
the home page "with the filters", and each part of the country has its own page."""
def test_no_page_in_the_build_says_with_the_filters(self):
for base, _, names in os.walk(OUT):
for n in names:
if n.endswith(".html"):
with open(os.path.join(base, n), encoding="utf-8") as f:
text = f.read()
self.assertNotIn("with the filters", text, os.path.join(base, n))
self.assertNotIn('href="/?where=', text, os.path.join(base, n))
def test_each_part_of_the_country_has_a_page_with_the_bar(self):
doc = read_out("regions/central-canada/index.html")
self.assertIn('id="finder-form"', doc)
self.assertIn('href="/regions/central-canada/"', read_out("regions/index.html"))
if __name__ == "__main__":
unittest.main()
+5 -3
View File
@@ -208,7 +208,7 @@ class MissingValuesTest(unittest.TestCase):
def test_script_leaves_out_missing_values(self):
with open(os.path.join(WEB, "assets", "app.js"), encoding="utf-8") as f:
js = f.read()
self.assertIn("if (s.month && words(d.months).indexOf(s.month) === -1) return false;", js)
self.assertIn("if (skip !== 'month' && s.month && !has(d.months, s.month)) return false;", js)
self.assertIn("note.hidden = !on[note.dataset.missing]", js)
def test_clearing_returns_the_lengths_to_any(self):
@@ -216,14 +216,16 @@ class MissingValuesTest(unittest.TestCase):
# "Any" is the last option of the longest-length list, so both the page and
# the script (which rebuilds the lists in the reader's units) must mark it;
# in the shortest-length list it is first.
form = home.finder_form(self.recs(3, 8))
# (lengths that differ: a Length filter is written only where it can narrow the trails)
form = home.finder_form(self.recs(3, 8) + [fake(300, km=900)])
longest = re.search(r'<select[^>]* id="max"[^>]*>(.*?)</select>', form, re.S).group(1)
self.assertEqual(re.findall(r'<option value="([^"]*)" selected', longest), [""])
shortest = re.search(r'<select[^>]* id="min"[^>]*>(.*?)</select>', form, re.S).group(1)
self.assertTrue(shortest.startswith('<option value="">Any</option>'))
with open(os.path.join(WEB, "assets", "app.js"), encoding="utf-8") as f:
js = f.read()
self.assertIn("if (value === '') o.defaultSelected = true;", js)
self.assertIn("if (p.o.def) opt.defaultSelected = true;", js)
self.assertIn("{ value: '', label: 'Any', counted: false, group: '', def: true }", js)
# Words that must not appear on a browsing page (home, places, lists, Routes, and a
+336
View File
@@ -0,0 +1,336 @@
"""The filter bar on every page that shows a set of trails, and the numbers beside its choices.
The bar (olt/home.py listing(), finder_form()) is the home page's, on each list, place and the Routes
page whose set has at least home.FILTER_MIN trails, built from that page's own trails. app.js counts
the choices again from the rows on the page every time anything changes (FacetCount, between the
facet-counts markers); this file runs that counting under node, on the rows the home page writes,
and checks it against counts made here straight from the records. Pages are rendered one at a time;
the site is not built.
"""
import collections
import html
import json
import os
import re
import shutil
import subprocess
import sys
import unittest
WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ROOT = os.path.dirname(WEB)
sys.path.insert(0, WEB)
sys.path.insert(0, os.path.join(ROOT, "tools"))
from olt import browse, facets, home, layout, leftout, regions, site, standing, views, words # noqa: E402
from olt import records as recordsmod # noqa: E402
SITE = site.load()
def read(*parts):
with open(os.path.join(*parts), encoding="utf-8") as f:
return f.read()
def form_of(body):
body = str(body)
if 'id="finder-form"' not in body:
return ""
return body[body.index('<form class="filters"'):body.index("</form>")]
def facets_of(body):
return re.findall(r'data-facet="(\w+)"', form_of(body))
def entry_ids(body):
return re.findall(r'<li class="entry" data-id="([^"]+)"', str(body))
class Pages:
_recs = None
@classmethod
def recs(cls):
if Pages._recs is None:
Pages._recs = recordsmod.load_records(ROOT)
return Pages._recs
class WhichPagesHaveTheBarTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.records = Pages.recs()
cls.shown = dict((lst.key, recs) for lst, recs in browse.shown(cls.records))
def list_body(self, key):
lst = browse.by_key(key)
return regions.list_page(lst, self.shown[key], len(self.records), SITE, records=self.records)[2]
def test_a_list_page_a_place_page_a_part_of_the_country_and_routes_have_it(self):
self.assertGreaterEqual(len(self.shown["loops"]), home.FILTER_MIN)
self.assertTrue(form_of(self.list_body("loops")))
by_slug, _ = regions.collect_regions(self.records)
self.assertGreaterEqual(len(by_slug["ca-on"]["records"]), home.FILTER_MIN)
self.assertTrue(form_of(regions.region_page("ca-on", self.records, SITE)[2]))
self.assertTrue(form_of(regions.group_page("central-canada", self.records, SITE)[2]))
self.assertTrue(form_of(regions.routes_page(self.records, SITE)[2]))
def test_a_set_under_the_threshold_has_the_plain_rows(self):
small = [k for k, recs in self.shown.items() if len(recs) < home.FILTER_MIN and k != "routes"]
self.assertTrue(small)
for key in small:
body = self.list_body(key)
self.assertFalse(form_of(body), key)
self.assertNotIn("data-finder", str(body), key)
def test_the_tables_rankings_newest_authors_and_left_out_pages_do_not(self):
bodies = {}
for spec in standing.RANKINGS:
built = standing.ranking_page(spec, self.records, SITE)
if built:
bodies[spec[0]] = built[2]
from olt import datafiles
for c in datafiles.collections(ROOT):
built = standing.collection_page(c, self.records, SITE)
if built:
bodies[c["name"]] = built[2]
built = views.recent_page(self.records, SITE)
if built:
bodies["recent"] = built[2]
from olt import authors
groups = authors.author_pages(self.records, ROOT)
bodies["authors"] = authors.index_page(self.records, SITE, ROOT)[2]
big = max(groups, key=lambda g: len(g["routes"]))
bodies["author"] = authors.author_page(big, self.records, SITE, groups)[2]
bodies["left-out"] = leftout.left_out_page(leftout.load_entries(ROOT), SITE, ROOT)[2]
self.assertGreater(len(bodies), 4)
for name, body in bodies.items():
self.assertNotIn('id="finder-form"', str(body), name)
self.assertNotIn("data-finder", str(body), name)
def test_the_saved_page_has_no_bar(self):
from olt import saved
self.assertNotIn('id="finder-form"', str(saved.saved_page(self.records, SITE)[2]))
def test_one_bar_one_script(self):
# every page's bar is the same form, which app.js finds by the one id
body = str(self.list_body("loops"))
self.assertEqual(body.count('id="finder-form"'), 1)
self.assertIn('<div class="results" data-finder', body)
js = read(WEB, "assets", "app.js")
self.assertIn("document.querySelector('.results[data-finder]')", js)
self.assertEqual(js.count("function initFinder("), 1)
class FacetsFitThePageTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.records = Pages.recs()
cls.shown = dict((lst.key, recs) for lst, recs in browse.shown(cls.records))
def test_loops_have_no_shape_filter_and_routes_no_kind(self):
lst = browse.by_key("loops")
body = regions.list_page(lst, self.shown["loops"], len(self.records), SITE, records=self.records)[2]
self.assertNotIn("shape", facets_of(body))
self.assertIn("where", facets_of(body))
self.assertNotIn("kind", facets_of(regions.routes_page(self.records, SITE)[2]))
def test_a_states_page_has_no_where(self):
body = regions.region_page("ca-on", self.records, SITE)[2]
self.assertNotIn("where", facets_of(body))
self.assertNotIn('name="where"', form_of(body))
def test_a_part_of_the_country_offers_itself_first_then_only_its_own_places(self):
body = regions.group_page("central-canada", self.records, SITE)[2]
recs = regions.group_records(self.records, "central-canada")
where = re.search(r'<select class="select" id="where" name="where">(.*?)</select>', form_of(body), re.S).group(1)
options = re.findall(r'<option value="([^"]*)" data-label="([^"]*)">([^<]*)</option>', where)
self.assertEqual(options[0], ("", "All of Central Canada", f"All of Central Canada ({len(recs)})"))
self.assertNotIn("<optgroup", where)
allowed = {"CA-ON", "CA-QC", facets.ACROSS_CANADA}
self.assertTrue(options[1:])
for value, label, text in options[1:]:
self.assertIn(value, allowed)
n = sum(1 for r in recs if value in facets.where_tokens(r))
self.assertEqual(text, f"{label} ({n})")
def test_a_facet_that_cannot_narrow_is_left_out(self):
recs = [r for r in self.records if facets.shape(r) == "loop"]
form = home.finder_form(recs)
self.assertNotIn('data-facet="shape"', form)
# and one choice that holds every trail is no choice
only_us = [r for r in self.records if common_countries(r) == ["US"]][:20]
self.assertNotIn('value="US"', home.finder_form(only_us))
def test_no_choice_is_written_that_would_show_nothing(self):
body = regions.group_page("central-canada", self.records, SITE)[2]
recs = regions.group_records(self.records, "central-canada")
form = form_of(body)
self.assertNotRegex(form, r'class="check__count">0<')
have = {t for r in recs for t in facets.terrain(r)}
written = set(re.findall(r'name="terrain" value="([^"]+)"', form))
self.assertTrue(written)
self.assertTrue(written <= have, written - have)
self.assertNotIn("desert", written)
def common_countries(rec):
from olt import common
return common.countries(rec)
class AListPageCarriesItsOwnTrailsOnlyTest(unittest.TestCase):
def test_rows_and_map_are_the_lists_own(self):
records = Pages.recs()
lst = browse.by_key("loops")
recs = browse.members(lst, records)
body = str(regions.list_page(lst, recs, len(records), SITE, records=records)[2])
own = {r["id"] for r in recs}
self.assertEqual(set(entry_ids(body)), own)
self.assertNotIn("data-every-trail", body)
ids = re.search(r'data-map="overview"[^>]* data-ids="([^"]*)"', body).group(1).split()
self.assertTrue(set(ids) <= own)
def test_the_canonical_address_is_the_plain_page(self):
doc = layout.layout("Loops", "<p>x</p>", path="/lists/loops/", site=SITE)
canon = re.search(r'<link rel="canonical" href="([^"]+)"', doc)
if canon:
self.assertTrue(canon.group(1).endswith("/lists/loops/"))
self.assertNotIn("?", canon.group(1))
class NoFilterLinksTest(unittest.TestCase):
def test_no_page_sends_a_visitor_to_the_home_page_with_a_filter_set(self):
for name in os.listdir(os.path.join(WEB, "olt")):
if name.endswith(".py"):
text = read(WEB, "olt", name)
self.assertNotIn("with the filters", text, name)
self.assertNotIn('href="/?where', text, name)
self.assertNotIn('href="/?kind', text, name)
def test_the_places_index_links_each_part_to_its_page(self):
body = str(regions.regions_index_page(Pages.recs(), SITE)[2])
self.assertIn('<a href="/regions/central-canada/">All 15 trails in Central Canada</a>'.replace(
"15", str(len(regions.group_records(Pages.recs(), "central-canada")))), body)
# Counting, as app.js does it, run under node ------------------------------------------------------
NODE = shutil.which("node")
def facet_count_source():
js = read(WEB, "assets", "app.js")
start = js.index("/* facet-counts:begin")
end = js.index("/* facet-counts:end */")
return js[start:end]
def rows_of(body):
"""The rows' data, as app.js reads it from each row's data-* attributes."""
out = []
for attrs in re.findall(r'<li class="entry"([^>]*)>', str(body)):
d = {k: html.unescape(v) for k, v in re.findall(r' data-([a-z]+)="([^"]*)"', attrs)}
split = lambda v: [x for x in v.split(" ") if x] # noqa: E731
out.append({"id": d["id"], "search": d["search"], "where": split(d["where"]), "km": float(d["km"]),
"time": d["time"], "months": split(d["months"]), "terrain": split(d["terrain"]),
"kind": d["kind"], "walking": d["walking"], "shape": d["shape"], "gpx": d["gpx"]})
return out
def state(**kw):
s = {"words": [], "where": "", "min": 0, "max": None, "month": "", "kind": "",
"time": [], "terrain": [], "walking": [], "shape": [], "gpx": []}
s.update(kw)
return s
def run_counts(rows, s, steps=()):
"""FacetCount.count(rows, s, steps) under node. max None stands for no longest length."""
prog = facet_count_source() + """
var input = JSON.parse(require('fs').readFileSync(0, 'utf8'));
if (input.s.max === null) input.s.max = Infinity;
process.stdout.write(JSON.stringify(FacetCount.count(input.rows, input.s, input.steps)));
"""
out = subprocess.run([NODE, "-e", prog], input=json.dumps({"rows": rows, "s": s, "steps": list(steps)}),
capture_output=True, text=True, check=True)
return json.loads(out.stdout)
@unittest.skipUnless(NODE, "node is not installed")
class CountsAreTrueTest(unittest.TestCase):
"""The maintainer's case: the home page at ?where=g:central-canada&time=week."""
@classmethod
def setUpClass(cls):
cls.records = Pages.recs()
cls.rows = rows_of(home.render(cls.records, SITE, ROOT))
cls.cc = [r for r in cls.records if "central-canada" in facets.place_groups(r)]
def test_the_home_page_rows_are_every_trail(self):
self.assertEqual(len(self.rows), len(self.records))
def test_with_central_canada_chosen_time_and_terrain_count_its_trails_only(self):
c = run_counts(self.rows, state(where="g:central-canada"))
self.assertEqual(c["total"], len(self.cc))
self.assertEqual(c["time"], dict(collections.Counter(facets.time_band(r) for r in self.cc)))
self.assertEqual(sum(c["time"].values()), len(self.cc))
self.assertEqual(c["terrain"], dict(collections.Counter(t for r in self.cc for t in facets.terrain(r))))
# every number is of trails that are there: nothing counts zero, and nothing absent is counted
self.assertTrue(all(n > 0 for n in c["terrain"].values()))
self.assertTrue(all(n > 0 for n in c["time"].values()))
def test_with_a_week_or_less_also_chosen(self):
c = run_counts(self.rows, state(where="g:central-canada", time=["week"]))
week = [r for r in self.cc if facets.time_band(r) == "week"]
self.assertEqual(c["total"], len(week))
# Time is counted against Where only, not against its own choice: the bands add up to the place
self.assertEqual(c["time"], dict(collections.Counter(facets.time_band(r) for r in self.cc)))
self.assertEqual(c["base"]["time"], len(self.cc))
# Terrain against both
self.assertEqual(c["terrain"], dict(collections.Counter(t for r in week for t in facets.terrain(r))))
# Where against the time only: "All of Central Canada" says how many of it take a week or less
everywhere_week = [r for r in self.records if facets.time_band(r) == "week"]
self.assertEqual(c["where"]["g:central-canada"], len(week))
self.assertEqual(c["base"]["where"], len(everywhere_week))
self.assertEqual(c["where"]["CA-ON"], sum(1 for r in everywhere_week if "CA-ON" in facets.place_keys(r)))
def test_length_steps_count_from_the_chosen_bounds(self):
steps = [[f"{n}mi", n * words.KM_PER_MI] for n in (100, 200, 500)]
c = run_counts(self.rows, state(where="g:central-canada", max=500 * words.KM_PER_MI), steps)
for value, km in steps:
self.assertEqual(c["min"][value], sum(1 for r in self.cc if km <= r["length_km"] <= 500 * words.KM_PER_MI))
self.assertEqual(c["max"][value], sum(1 for r in self.cc if r["length_km"] <= km))
def test_search_counts_too(self):
c = run_counts(self.rows, state(words=["trail"], kind="route"))
want = [r for r in self.rows if "trail" in r["search"] and r["kind"] == "route"]
self.assertEqual(c["total"], len(want))
self.assertEqual(c["kind"]["trail"], sum(1 for r in self.rows if "trail" in r["search"] and r["kind"] == "trail"))
def test_the_script_takes_out_what_would_show_nothing(self):
js = read(WEB, "assets", "app.js")
self.assertIn("if (o.value && k === 0 && o.value !== chosen) return;", js)
self.assertIn("label.hidden = n === 0 && !b.checked;", js)
self.assertIn("field.hidden = !narrows && !isSet(f, s);", js)
# the counts are made on every change, from the rows on the page
self.assertIn("var c = FacetCount.count(rows, s, lengthSteps());", js)
class PanelInTheFlowTest(unittest.TestCase):
def test_the_open_panel_is_not_laid_over_the_rows(self):
css = read(WEB, "assets", "style.css")
rule = re.search(r"\n\.filters__panels \{[^}]*\}", css).group(0)
self.assertNotIn("position: absolute", rule)
self.assertNotRegex(css, r"html\.js \.filters__panels \{[^}]*position: absolute")
def test_the_panel_starts_closed_whatever_the_address_says(self):
js = read(WEB, "assets", "app.js")
self.assertNotIn("if (firstOn", js)
self.assertIn("if (window.location.hash === '#filters') showPanels(true);", js)
if __name__ == "__main__":
unittest.main()
+2 -2
View File
@@ -91,9 +91,9 @@ class HomePageTest(unittest.TestCase):
self.assertLess(grid.index('id="finder-form"'), grid.index('id="entries"'))
self.assertNotIn("filters__maplink", self.body)
def test_the_open_filters_lie_over_the_rows_and_can_be_closed(self):
def test_the_open_filters_sit_between_the_bar_and_the_rows_and_can_be_closed(self):
css = read(WEB, "assets", "style.css")
self.assertRegex(css, r"html\.js \.filters__panels \{[^}]*position: absolute;")
self.assertNotRegex(css, r"\.filters__panels \{[^}]*position: absolute;")
self.assertIn('class="button filters__done"', self.body)
js = read(WEB, "assets", "app.js")
self.assertIn("e.key === 'Escape'", js)
+2 -2
View File
@@ -566,11 +566,11 @@ class RenderUnitTest(unittest.TestCase):
f.write('id = "x"\n')
rec = sample_record(name="A & B")
n = pages.render_site([rec], out, repo, site=site.Site("N", "T"))
# trail page + home + 404 + places hub + 1 place + lists hub + routes,
# trail page + home + 404 + places hub + 1 place + its part of the country + lists hub + routes,
# sources, logos, about, data, schema, changelog, left out, saved (no list holds MIN_SIZE trails),
# and the two reference pages, the glossary and the method (the tables, authors, recent and
# linked-trails pages need at least MIN_SIZE trails and are not built for one)
self.assertEqual(n, 17)
self.assertEqual(n, 18)
with open(os.path.join(out, "trails", "x", "index.html"), encoding="utf-8") as f:
self.assertIn("A &amp; B", f.read())
with open(os.path.join(out, "index.html"), encoding="utf-8") as f: