diff --git a/web/assets/app.js b/web/assets/app.js index 5101b5a..22bbde8 100644 --- a/web/assets/app.js +++ b/web/assets/app.js @@ -800,15 +800,9 @@ { id: 'olt-sketch-points', type: 'circle', strokeByKind: true, strokeWidth: 2, radius: [3, 3, 9, 6], filter: IS_SKETCH, hit: true } ]; } - if (kind === 'sketch') { - var col = routeMain ? '--route' : '--trail'; - /* A pale band under the dots lifts them off relief and contours. */ - return [ - { id: 'olt-sketch-halo', color: '--casing', width: [5, 6, 12, 9], opacity: 0.6, filter: IS_SKETCH }, - { id: 'olt-sketch', color: col, width: [5, 3, 12, 5], dash: [0, 2], cap: 'round', filter: IS_SKETCH }, - { id: 'olt-sketch-points', type: 'circle', stroke: col, strokeWidth: 2.5, radius: [5, 5, 12, 8], filter: IS_SKETCH } - ]; - } + /* A trail page with no track: the map draws no layer at all. The start and the end are + labelled markers (placeTermini in initMap), and nothing joins them. */ + if (kind === 'sketch') return []; return [ { id: 'olt-casing', color: '--casing', width: [5, 4, 12, 8] }, { id: 'olt-alt', color: '--trail', width: [5, 1.5, 12, 3], dash: [2, 1.6], filter: ['==', ['get', 'role'], 'alternate'] }, @@ -942,7 +936,89 @@ if (!frame || !hasSketch()) return; var r = host.getBoundingClientRect(); if (r.width && r.height) corners(extentOf(frame, r.width, r.height, 0)); + placeTermini(); } + + /* The start and the end of a trail with no track: a dot and a label each, from the + page's own list of them (.terminus-item: the record's places and positions). They sit + over the drawing and over the live map alike, and are text for screen readers in that + list, so the layer is hidden from them. A northern end's label goes above its dot, a + southern one's below, and each is kept inside the frame. */ + var termini = []; + var terminiLayer = host.querySelector('.map__termini'); + if (terminiLayer) { + Array.prototype.forEach.call(fig.querySelectorAll('.terminus-item'), function (li) { + var el = document.createElement('div'); + el.className = 'terminus terminus--' + li.dataset.role; + var dot = document.createElement('span'); + dot.className = 'terminus__dot'; + var label = document.createElement('span'); + label.className = 'terminus__label'; + label.textContent = li.dataset.label; + el.appendChild(dot); + el.appendChild(label); + terminiLayer.appendChild(el); + termini.push({ el: el, label: label, lon: Number(li.dataset.lon), lat: Number(li.dataset.lat) }); + }); + } + function placeTermini() { + if (!termini.length) return; + var r = host.getBoundingClientRect(); + if (!r.width || !r.height) return; + var W = r.width, H = r.height; + var ext = entry.ready && entry.map ? null : (frame ? extentOf(frame, W, H, 0) : null); + var xy = termini.map(function (t) { + if (ext) return { x: W / 2 + (t.lon - ext.cx) * ext.rad * ext.k, y: H / 2 - (mercY(t.lat) - ext.cy) * ext.k }; + var p = entry.map.project([t.lon, t.lat]); + return { x: p.x, y: p.y }; + }); + /* Each label goes above or below its dot, as far as possible outward (the northern end's + above, the southern end's below), kept inside the frame, and never over the other label + or the other dot: the four ways of placing two labels are scored and the best one used. */ + var HALF = 13; + var boxes = termini.map(function (t, i) { + var w = t.label.offsetWidth, h = t.label.offsetHeight, p = xy[i]; + var x0 = p.x - w / 2; + var dx = x0 < 8 ? 8 - x0 : (x0 + w > W - 8 ? (W - 8) - (x0 + w) : 0); + return { w: w, h: h, dx: dx, left: x0 + dx }; + }); + function rect(i, above) { + var b = boxes[i], p = xy[i]; + var top = above ? p.y - HALF - b.h : p.y + HALF; + return { l: b.left, r: b.left + b.w, t: top, b: top + b.h }; + } + function overlap(a, c) { + var w = Math.min(a.r, c.r) - Math.max(a.l, c.l), h = Math.min(a.b, c.b) - Math.max(a.t, c.t); + return w > 0 && h > 0 ? w * h : 0; + } + function dotBox(i) { return { l: xy[i].x - 10, r: xy[i].x + 10, t: xy[i].y - 10, b: xy[i].y + 10 }; } + function cost(sides) { + var c = 0; + var rs = sides.map(function (above, i) { return rect(i, above); }); + rs.forEach(function (r, i) { + c += Math.max(0, 4 - r.t) * 40 + Math.max(0, r.b - (H - 4)) * 40; + xy.forEach(function (_, j) { if (j !== i) c += overlap(r, dotBox(j)) * 20; }); + if (i > 0) c += overlap(r, rs[0]) * 20; + }); + return c; + } + var outward = xy.length > 1 && xy[1].y < xy[0].y ? [false, true] : [true, false]; + var choices = xy.length === 1 ? [[true], [false]] + : [outward, [!outward[0], !outward[1]], [true, true], [false, false]]; + var best = choices[0], bestCost = Infinity; + choices.forEach(function (c) { + var k = cost(c); + if (k < bestCost) { best = c; bestCost = k; } + }); + termini.forEach(function (t, i) { + var p = xy[i]; + t.el.style.transform = 'translate(' + p.x.toFixed(1) + 'px,' + p.y.toFixed(1) + 'px)'; + t.el.classList.toggle('terminus--above', best[i]); + t.el.classList.toggle('terminus--below', !best[i]); + t.label.style.setProperty('--dx', boxes[i].dx.toFixed(1) + 'px'); + }); + } + entry.placeTermini = placeTermini; function redrawFallback() { if (hasSketch()) { sketchCorners(); return; } if (!entry.ready && entry.fc) { @@ -1100,6 +1176,7 @@ } entry.ready = true; settled = true; + placeTermini(); /* The live map shows (and the drawing gives way, in the CSS) once it has drawn its first frame with the tracks: the base map fills in behind a track that holds still. */ var shown = false; @@ -1161,6 +1238,11 @@ corners({ w: b.getWest(), e: b.getEast(), n: b.getNorth(), s: b.getSouth() }); } map.on('moveend', function () { if (entry.ready) mapCorners(); }); + if (termini.length) { + map.on('move', placeTermini); + map.on('resize', placeTermini); + map.on('load', placeTermini); + } document.addEventListener('olt:theme', function () { if (!entry.ready || !settled) return; /* a style still loading is dressed in the new theme */ if (current === 'outdoor') restyle(); @@ -1253,7 +1335,7 @@ var pointOnly = (g.type === 'MultiPoint' && g.coordinates.length === 1) || g.type === 'Point'; var note = document.createElement('p'); note.textContent = pointOnly - ? 'No GPX here. The ring only marks one end of it; it is not the trail\u2019s path.' + ? 'No GPX here. The ring only marks where it starts and ends; it is not the trail\u2019s path.' : 'No GPX here. The dotted line only joins the start and the end; it is not the trail\u2019s path.'; box.appendChild(note); } diff --git a/web/assets/style.css b/web/assets/style.css index e48665a..f332ee5 100644 --- a/web/assets/style.css +++ b/web/assets/style.css @@ -825,9 +825,63 @@ html.js .map__status:not([data-say]) { display: none; } .legend li { display: inline-flex; align-items: center; gap: var(--space-2); } /* Under a map of many trails the legend keeps a row to itself, however short it is. */ .mapfig[data-map="overview"] .legend { flex-basis: 100%; } -.mapfig__caption--sketch { align-items: start; } -.sketch-note { display: grid; gap: var(--space-2); max-inline-size: 42rem; } -.sketch-note .cluster { margin-block-start: var(--space-1); } +/* A trail with no track and a known start and end (olt/trail.py sketch_figure): the map with a + labelled marker at each end, and the notice about where to get a track beside or under it, + never over it. No line joins the two. */ +.mapfig--termini { display: grid; gap: var(--space-4); align-content: start; } +.mapfig--termini .mapfig__frame { grid-area: frame; } +.mapfig--termini .termini-notice { grid-area: notice; min-inline-size: 0; } +.mapfig--termini .mapfig__caption { grid-area: caption; margin-block-start: 0; } +.mapfig--termini { grid-template-areas: "frame" "caption" "notice"; gap: var(--space-3); } +.mapfig--termini .map__message { max-inline-size: none; padding: var(--space-4); box-shadow: 4px 4px 0 var(--rule); } +.mapfig--termini .map__message > * + * { margin-block-start: var(--space-2); } +.mapfig--termini .map__message h2 { font-size: var(--step-1); } +.mapfig--termini .map { aspect-ratio: 16 / 10; } +/* Wide: the notice stands beside the map, so both ends and the notice are in the first screen. */ +@media (min-width: 64rem) { + .mapfig--termini { + grid-template-columns: minmax(0, 1fr) 17.5rem; + grid-template-areas: "frame notice" "caption caption"; + gap: var(--space-3) var(--space-4); + } + .mapfig--termini .map { aspect-ratio: auto; block-size: clamp(17rem, calc(100svh - 28rem), 26rem); } +} +.termini-list { display: flex; flex-wrap: wrap; gap: var(--space-1) var(--space-5); padding: 0; margin: 0 0 var(--space-1); list-style: none; } +/* With the script the labels on the map say the same; the list stays for screen readers. */ +html.js .termini-list { position: absolute; inline-size: 1px; block-size: 1px; overflow: hidden; clip-path: inset(50%); } +.mapfig--termini .map__reason { font-size: var(--step-0); line-height: 1.5; } +.termini-list strong { margin-inline-end: var(--space-1); } +.map__termini { position: absolute; inset: 0; z-index: 2; overflow: hidden; pointer-events: none; } +.terminus { position: absolute; inset-block-start: 0; inset-inline-start: 0; } +.terminus__dot { + position: absolute; + inset-block-start: -8px; + inset-inline-start: -8px; + inline-size: 16px; + block-size: 16px; + box-sizing: border-box; + border-radius: 50%; + background: var(--casing); + border: 3.5px solid var(--trail); + box-shadow: 0 0 0 2px var(--casing); +} +.mapfig[data-route="yes"] .terminus__dot { border-color: var(--route); } +.terminus__label { + position: absolute; + inset-inline-start: 0; + inline-size: max-content; + max-inline-size: 15rem; + padding: 2px var(--space-2); + transform: translateX(calc(-50% + var(--dx, 0px))); + background: var(--surface); + border: 1px solid var(--ink); + color: var(--ink); + font: 600 var(--step--1)/1.3 var(--font-sans); + text-align: center; +} +.terminus--above .terminus__label { inset-block-end: 13px; } +.terminus--below .terminus__label { inset-block-start: 13px; } +@media (max-width: 40rem) { .terminus__label { max-inline-size: 10rem; font-size: var(--step--2); } } /* Empty frame: the record has no line, so nothing is drawn */ .map--empty { diff --git a/web/build.py b/web/build.py index 220e14b..5743790 100644 --- a/web/build.py +++ b/web/build.py @@ -112,6 +112,18 @@ def sketch_features(rec): return features +def termini_features(rec): + """GeoJSON for the trail page's map of a trail with no track: one Point per marker (the start + and the end, or one point for a loop), labelled with the record's own place names. Never a + line: nothing here can be read as the route.""" + props = {"id": rec["id"], "name": rec["name"], "kind": rec["derived"]["kind"], + "country": rec["country"], "length_km": rec["length_km"], "sketch": True} + return [{"type": "Feature", + "properties": dict(props, role=m["role"], place=m["place"], label=m["label"]), + "geometry": {"type": "Point", "coordinates": m["lonlat"]}} + for m in hike.termini(rec)] + + def trail_outputs(tid, files, rec=None): """Names of the data files written into _site/trails// for these files.""" names = [] @@ -247,7 +259,7 @@ def build_trail(rec, out_dir, code_mtime, force, stats): box = geo.merge_bbox([geo.bbox(m["geometry"]["coordinates"]) for m in maps]) fc = {"type": "FeatureCollection", "bbox": box, "features": maps} write_json(os.path.join(tdir, "map.json"), fc, stats) - sketches = sketch_features(rec) if "line" not in files else [] + sketches = termini_features(rec) if "line" not in files else [] if sketches: box = hike.sketch_bbox(hike.sketch_points(rec), pad=True) write_json(os.path.join(tdir, "sketch.json"), diff --git a/web/olt/hike.py b/web/olt/hike.py index 98e7aaf..5c64849 100644 --- a/web/olt/hike.py +++ b/web/olt/hike.py @@ -123,8 +123,10 @@ def end_point(rec): def sketch_points(rec): """The points a map may sketch for a trail with no track: [start, end] - when both are on file, or the one that is. Empty when the trail has a - track or neither point (see sketch_end for which end a lone point is). + when both are on file, or the one point of a loop (shape "loop", or the + same place for both ends), which is its start and its end. Empty when the + trail has a track, or when only one end of a point-to-point trail is known: + one end alone says nothing a reader can use, so that trail gets no map. A sketch is only ever these points. It is never a track: nothing here feeds a download, a GPX status or an elevation figure. @@ -132,8 +134,12 @@ def sketch_points(rec): derived = rec.get("derived", {}) if derived.get("has_line") or "line" in derived.get("files", {}): return [] - points = [p for p in (start_point(rec), end_point(rec)) if p] - return points[:1] if len(points) == 2 and points[0] == points[1] else points + start, end = start_point(rec), end_point(rec) + if start and end: + return [start] if start == end else [start, end] + if start and shape(rec) == "loop": + return [start] + return [] def sketch_end(rec): @@ -143,6 +149,29 @@ def sketch_end(rec): return "start" if start_point(rec) else "end" +def termini(rec): + """The markers of the trail page's map for a trail with no track, from the + record only: [{"role": "start" | "end" | "both", "lonlat": [lon, lat], + "place": name or "", "label": text}]. A loop has one marker that is both + its start and its end. Empty whenever sketch_points is.""" + points = sketch_points(rec) + if not points: + return [] + h = table(rec) + + def name(key): + v = h.get(key) + return v.strip() if isinstance(v, str) else "" + + def marker(role, point, place): + head = {"start": "Start", "end": "End", "both": "Start and end"}[role] + return {"role": role, "lonlat": point, "place": place, + "label": f"{head}: {place}" if place else head} + if len(points) == 1: + return [marker("both", points[0], name("start") or name("end"))] + return [marker("start", points[0], name("start")), marker("end", points[1], name("end"))] + + def sketch_bbox(points, *, pad=False): """[min lon, min lat, max lon, max lat] of sketch points, or None. diff --git a/web/olt/home.py b/web/olt/home.py index d67337e..ad1dd96 100644 --- a/web/olt/home.py +++ b/web/olt/home.py @@ -669,12 +669,12 @@ def overview_map(recs, label, *, wide=False, scope="", saved=False): s = len(sketches) sentences.append(f'{s} trail{"s" if s != 1 else ""} with no GPX here ' f'{"are" if s != 1 else "is"} shown as a dotted straight line between ' - 'their start and end, or a ring where only one end is known. ' + 'their start and end, or a ring for a loop, which starts and ends in one place. ' 'That is not the trail’s path.') if saved: sentences = ["Tracks are simplified for display. Select one for its name.", "A trail with no GPX here is shown by its start and end only: dots straight from one " - "to the other, or a ring where only one end is known."] + "to the other, or a ring for a loop."] ids_attr += f' data-drawable="{esc(" ".join(ids))}"' sentences.append("Each trail’s page names its source, credit and licence. " "Base map: OpenFreeMap, © OpenMapTiles, data © OpenStreetMap contributors.") diff --git a/web/olt/seo.py b/web/olt/seo.py index 1dbc520..f61744b 100644 --- a/web/olt/seo.py +++ b/web/olt/seo.py @@ -214,7 +214,7 @@ def _extent(rec): the one point on file. Coordinates come from the record or its track, never made up.""" box = rec.get("derived", {}).get("bbox") or rec.get("derived", {}).get("map_bbox") if not box: - pts = hike.sketch_points(rec) + pts = [p for p in (hike.start_point(rec), hike.end_point(rec)) if p] # the record's own points, map or no map if len(pts) == 1: return {"@type": "GeoCoordinates", "longitude": pts[0][0], "latitude": pts[0][1]} if pts: diff --git a/web/olt/trail.py b/web/olt/trail.py index ea707bc..44b1776 100644 --- a/web/olt/trail.py +++ b/web/olt/trail.py @@ -807,63 +807,53 @@ def empty_frame(rec): def sketch_figure(rec): - """A real map for a trail with no track but a known start or end: a dotted - straight line between the two, or one ring. It says plainly that the line only - joins the start and the end, and keeps the words about where to get a track.""" + """A real map for a trail with no track whose start and end are on file (or a loop's one place): + the base map fitted to those points, with each one marked and named. No line joins them and + nothing is drawn that could be read as the route. The notice about where to get a track sits + beside the map, not over it.""" points = hike.sketch_points(rec) box = hike.sketch_bbox(points, pad=True) bbox_attr = f' data-bbox="{",".join(str(v) for v in box)}"' if box else "" route = common.is_route(rec) - h = hike.table(rec) - start = h.get("start") if isinstance(h.get("start"), str) else "" - end = h.get("end") if isinstance(h.get("end"), str) else "" - start, end = start.strip(), end.strip() - if len(points) == 2: - if start and end: - where = (f"The dotted line runs straight from {esc(start)} to {esc(end)}. " - "It only joins the start and the end; that is not the trail’s path.") - elif start: - where = (f"The dotted line runs straight from {esc(start)} to where it ends. " - "It only joins the start and the end; that is not the trail’s path.") - else: - where = ("The dotted line runs straight between its start and its end. " - "It only joins the two; that is not the trail’s path.") - legend_text = "No GPX here: start and end only" + marks = hike.termini(rec) + items = "".join( + f'
  • ' + f'{"Start and end" if m["role"] == "both" else m["role"].capitalize()}' + f'{" " + esc(m["place"]) if m["place"] else ""}
  • ' for m in marks) + if len(marks) == 1: + caption = ("Only the place where it starts and ends is shown. There is no track for this trail here, " + "and the site does not guess one.") else: - if hike.sketch_end(rec) == "end": - where = (f"The ring marks {esc(end)}, where it ends. " if end else "The ring marks where it ends. ") - where += "No position is on file for the start, so no line is drawn." - legend_text = "No GPX here: end only" - elif h.get("shape") == "loop": - where = (f"The ring marks {esc(start)}, where the loop starts and ends. " if start - else "The ring marks where the loop starts and ends. ") - where += "It shows where the trail is, not its path." - legend_text = "No GPX here: start only" - else: - where = (f"The ring marks {esc(start)}, where it starts. " if start else "The ring marks where it starts. ") - where += "No position is on file for the end, so no line is drawn." - legend_text = "No GPX here: start only" - _title, status, reason, rule, actions_html = _no_gpx_parts(rec) + caption = ("Only the start and the end are shown. There is no track for this trail here, " + "and the site does not guess one.") + title, status, reason, rule, actions_html = _no_gpx_parts(rec) reason_html = reason if isinstance(reason, Markup) else common.rich(reason) frame_attr, drawing = sketch_of(box, sketch.trail_features(rec["id"]), route_main=route) - return f"""
    + rid = esc(rec["id"]) + return f"""
    -
    +
    {drawing}
    -

    The map needs JavaScript. The ends of the trail are named below it.

    + +

    The map needs JavaScript. The ends of the trail are named beside it.

    -
    -
    • {common.SWATCH_SKETCH}{esc(legend_text)}
    -
    -

    No GPX here. {where}

    -

    {reason_html}

    -

    {esc(rule)}

    - {actions_html} +
    +
    +

    GPX: {esc(facets.GPX_STATUS[status])}

    +

    {esc(title)}

    +

    {reason_html}

    +

    {esc(rule)}

    + {actions_html}
    +
    +
    +
      {items}
    +

    {caption}

    """ diff --git a/web/tests/test_sorting.py b/web/tests/test_sorting.py index 2ac3400..8dd5ab9 100644 --- a/web/tests/test_sorting.py +++ b/web/tests/test_sorting.py @@ -185,7 +185,7 @@ class ResultsHtmlTest(unittest.TestCase): def sketch_rec(id_="sk", name="Sketch Trail", start=(-110.0, 40.0), end=(-100.0, 45.0), **kw): - hike_table = {"start": "Start Town", "shape": "point-to-point"} + hike_table = {"start": "Start Town", "shape": kw.pop("shape", "point-to-point")} if start is not None: hike_table["start_lonlat"] = list(start) if end is not None: @@ -198,17 +198,31 @@ def sketch_rec(id_="sk", name="Sketch Trail", start=(-110.0, 40.0), end=(-100.0, class SketchPointsTest(unittest.TestCase): def test_points_are_read_and_checked(self): self.assertEqual(hike.sketch_points(sketch_rec()), [[-110.0, 40.0], [-100.0, 45.0]]) - self.assertEqual(hike.sketch_points(sketch_rec(end=None)), [[-110.0, 40.0]]) - self.assertEqual(hike.sketch_points(sketch_rec(start=None)), [[-100.0, 45.0]]) - self.assertEqual(hike.sketch_end(sketch_rec(start=None)), "end") - self.assertEqual(hike.sketch_end(sketch_rec(end=None)), "start") + # One end of a point-to-point trail alone is never a map. + self.assertEqual(hike.sketch_points(sketch_rec(end=None)), []) + self.assertEqual(hike.sketch_points(sketch_rec(start=None)), []) + # A loop (shape "loop") has one place, its start and its end. + self.assertEqual(hike.sketch_points(sketch_rec(end=None, shape="loop")), [[-110.0, 40.0]]) + self.assertEqual(hike.sketch_end(sketch_rec(end=None, shape="loop")), "start") self.assertEqual(hike.sketch_end(sketch_rec()), "") - bad = sketch_rec(end=None) + # The same place for both ends is one point too. + self.assertEqual(hike.sketch_points(sketch_rec(end=(-110.0, 40.0))), [[-110.0, 40.0]]) + bad = sketch_rec(end=None, shape="loop") bad["hike"]["start_lonlat"] = [999, 40] self.assertEqual(hike.sketch_points(bad), []) bad["hike"]["start_lonlat"] = "not a place" self.assertEqual(hike.sketch_points(bad), []) + def test_termini_are_read_from_the_record_only(self): + marks = hike.termini(sketch_rec()) + self.assertEqual([(m["role"], m["label"]) for m in marks], + [("start", "Start: Start Town"), ("end", "End: End Town")]) + self.assertEqual([m["lonlat"] for m in marks], [[-110.0, 40.0], [-100.0, 45.0]]) + loop = hike.termini(sketch_rec(end=None, shape="loop")) + self.assertEqual([(m["role"], m["label"]) for m in loop], [("both", "Start and end: Start Town")]) + self.assertEqual(hike.termini(sketch_rec(end=None)), []) + self.assertEqual(hike.termini(make("plain", "Plain")), []) + def test_a_track_suppresses_the_sketch(self): rec = sketch_rec() rec["derived"]["has_line"] = True @@ -230,11 +244,20 @@ class SketchPointsTest(unittest.TestCase): self.assertIs(f["properties"]["sketch"], True) self.assertEqual(f["properties"]["id"], "sk") self.assertEqual(f["properties"]["name"], "Sketch Trail") - one = build.sketch_features(sketch_rec(end=None)) + one = build.sketch_features(sketch_rec(end=None, shape="loop")) self.assertEqual([f["geometry"]["type"] for f in one], ["MultiPoint"]) self.assertEqual(one[0]["geometry"]["coordinates"], [[-110.0, 40.0]]) + self.assertEqual(build.sketch_features(sketch_rec(end=None)), []) self.assertEqual(build.sketch_features(make("plain", "Plain")), []) + def test_trail_page_data_is_points_only_never_a_line(self): + feats = build.termini_features(sketch_rec()) + self.assertEqual([f["geometry"]["type"] for f in feats], ["Point", "Point"]) + self.assertEqual([f["properties"]["label"] for f in feats], ["Start: Start Town", "End: End Town"]) + self.assertEqual([f["geometry"]["coordinates"] for f in feats], [[-110.0, 40.0], [-100.0, 45.0]]) + self.assertEqual(len(build.termini_features(sketch_rec(end=None, shape="loop"))), 1) + self.assertEqual(build.termini_features(sketch_rec(end=None)), []) + def test_overview_includes_sketches_only(self): fc = build.overview_geojson([sketch_rec(), make("plain", "Plain")], "/nonexistent") self.assertEqual(sorted({f["properties"]["id"] for f in fc["features"]}), ["sk"]) @@ -272,27 +295,67 @@ class SketchMapTest(unittest.TestCase): self.assertIn("3 tracks, simplified for display.", doc) self.assertNotIn("start and end only", doc) - def test_trail_page_shows_a_sketch_map(self): + def test_trail_page_shows_a_map_with_both_ends_and_keeps_the_notice(self): _t, _d, body, needs_map = trail.render(sketch_rec(), GH) self.assertTrue(needs_map) self.assertIn('data-map="sketch"', body) self.assertIn("/trails/sk/sketch.json", body) - self.assertIn("Start Town", body) - self.assertIn("End Town", body) - self.assertIn("not the trail’s path", body) - self.assertIn("No GPX here", body) self.assertNotIn("map--empty", body) + # both ends are marked, each named from the record, with text for screen readers + self.assertEqual(body.count('class="terminus-item"'), 2) + self.assertIn('data-label="Start: Start Town"', body) + self.assertIn('data-label="End: End Town"', body) + self.assertIn('data-lon="-110.0" data-lat="40.0"', body) + self.assertIn('data-lon="-100.0" data-lat="45.0"', body) + self.assertIn('aria-describedby="termini-sk"', body) + # the notice stays, beside the map and not inside its frame + self.assertIn("GPX: ", body) + self.assertIn("A trail is listed without a GPX when no track for it may be passed on.", body) + self.assertIn("Where to ask for the track", body) + frame = body[body.index('
    '):body.index('
    ')] + self.assertNotIn("map__message", frame) + # the words say what is shown, and never call the track a line + self.assertIn("Only the start and the end are shown. There is no track for this trail here, " + "and the site does not guess one.", body) + self.assertNotIn("dotted", body) + caption = body[body.index("")] + self.assertNotIn("line", caption.lower()) - def test_trail_page_with_only_a_start_shows_a_ring(self): - _t, _d, body, needs_map = trail.render(sketch_rec(end=None), GH) + def test_no_track_element_for_a_trail_with_no_track(self): + for rec in (sketch_rec(), sketch_rec(end=None, shape="loop")): + self.assertEqual(build.trail_outputs(rec["id"], {}, rec), ["sketch.json"]) + self.assertEqual([f["geometry"]["type"] for f in build.termini_features(rec)], + ["Point"] * len(hike.termini(rec))) + _t, _d, body, _m = trail.render(rec, GH) + self.assertNotIn("map.json", body) + self.assertNotIn("line.geojson", body) + self.assertNotIn('class="fallback__line', body) + + def test_a_loop_with_one_point_shows_one_marker_for_both_ends(self): + _t, _d, body, needs_map = trail.render(sketch_rec(end=None, shape="loop"), GH) self.assertTrue(needs_map) - self.assertIn("The ring marks Start Town", body) + self.assertEqual(body.count('class="terminus-item"'), 1) + self.assertIn('data-label="Start and end: Start Town"', body) + self.assertIn("Only the place where it starts and ends is shown.", body) + self.assertIn("A trail is listed without a GPX when no track for it may be passed on.", body) + + def test_a_point_to_point_trail_with_one_point_keeps_the_empty_frame(self): + for rec in (sketch_rec(end=None), sketch_rec(start=None)): + _t, _d, body, needs_map = trail.render(rec, GH) + self.assertFalse(needs_map) + self.assertIn("map--empty", body) + self.assertNotIn("sketch.json", body) + self.assertNotIn("terminus-item", body) + self.assertIn("No map is drawn: there is no track for this trail here, and the site does not guess one.", + body) def test_trail_page_without_a_point_keeps_the_empty_frame(self): _t, _d, body, needs_map = trail.render(make("plain", "Plain Trail"), GH) self.assertFalse(needs_map) self.assertIn("map--empty", body) self.assertNotIn("sketch.json", body) + self.assertIn("No map is drawn: there is no track for this trail here, and the site does not guess one.", body) + self.assertIn("Nothing drawn", body) class ScriptAndDocsTest(unittest.TestCase): @@ -300,6 +363,7 @@ class ScriptAndDocsTest(unittest.TestCase): with open(os.path.join(WEB, "assets", "app.js"), encoding="utf-8") as f: js = f.read() for part in ("dash: [0, 2]", "olt-sketch-points", "No GPX here. The dotted line only joins", + "placeTermini", "terminus__label", "map__termini", "normalizeSortKey", "replaceState", "data-sort-col", "'long': 'length-desc'", "fallback__ring", "fallback__line--sketch"): self.assertIn(part, js, part)