diff --git a/web/assets/app.js b/web/assets/app.js index 402d1af..5239271 100644 --- a/web/assets/app.js +++ b/web/assets/app.js @@ -1480,17 +1480,19 @@ var SORT_KEYS = { 'name': 1, 'name-desc': 1, 'length-desc': 1, 'length-asc': 1, 'time-asc': 1, 'time-desc': 1, 'climb-desc': 1, 'climb-asc': 1 }; var SORT_OLD = { 'long': 'length-desc', 'short': 'length-asc', 'quick': 'time-asc', 'climb': 'climb-desc' }; - var SORT_COLUMN = { 'name': 'name', 'name-desc': 'name', 'length-desc': 'length', 'length-asc': 'length', + var SORT_COLUMN = { 'here': 'name', 'name': 'name', 'name-desc': 'name', 'length-desc': 'length', 'length-asc': 'length', 'time-asc': 'time', 'time-desc': 'time', 'climb-desc': 'climb', 'climb-asc': 'climb' }; - var SORT_ARROW = { 'name': '↑', 'name-desc': '↓', 'length-desc': '↓', 'length-asc': '↑', + var SORT_ARROW = { 'here': '↑', 'name': '↑', 'name-desc': '↓', 'length-desc': '↓', 'length-asc': '↑', 'time-asc': '↑', 'time-desc': '↓', 'climb-desc': '↓', 'climb-asc': '↑' }; var COLUMN_PRIMARY = { 'name': 'name', 'length': 'length-desc', 'time': 'time-asc', 'climb': 'climb-desc' }; - var COLUMN_TOGGLE = { 'name': 'name-desc', 'name-desc': 'name', 'length-desc': 'length-asc', 'length-asc': 'length-desc', + var COLUMN_TOGGLE = { 'here': 'name', 'name': 'name-desc', 'name-desc': 'name', 'length-desc': 'length-asc', 'length-asc': 'length-desc', 'time-asc': 'time-desc', 'time-desc': 'time-asc', 'climb-desc': 'climb-asc', 'climb-asc': 'climb-desc' }; /* The Saved page's list also has the order saved (rows numbered in data-order by section 1c). */ if (savedPage) SORT_KEYS.saved = 1; /* A ranking (/numbers/) has its rank as an order (rows numbered in data-rank by the page). */ if (document.querySelector('.entry[data-rank]')) SORT_KEYS.rank = 1; + /* A place page opens with the trails wholly in the place first (data-here 0, then 1), each A to Z. */ + if (document.querySelector('.entry[data-here]')) SORT_KEYS.here = 1; function normalizeSortKey(value, dflt) { if (SORT_KEYS[value]) return value; @@ -1509,6 +1511,7 @@ return cmpNum(ao, bo) || cmpStr(an, bn); } if (key === 'rank') return cmpNum(Number(a.dataset.rank || Infinity), Number(b.dataset.rank || Infinity)); + if (key === 'here') return cmpNum(Number(a.dataset.here || 0), Number(b.dataset.here || 0)) || cmpStr(an, bn); if (key === 'name') return cmpStr(an, bn); if (key === 'name-desc') return cmpStr(bn, an); if (key === 'climb-desc' || key === 'climb-asc') { diff --git a/web/olt/home.py b/web/olt/home.py index f99017a..badf50f 100644 --- a/web/olt/home.py +++ b/web/olt/home.py @@ -151,7 +151,7 @@ def route_by_html(rec): return Markup(text) -def entry(rec, *, level=3, extra="", routes_list=False, hidden=False, eager=False, lead=None, rank=None, more=(), by=None): +def entry(rec, *, level=3, extra="", routes_list=False, hidden=False, eager=False, lead=None, rank=None, more=(), by=None, here=None): """One trail in a list. Its data-* attributes drive the filters in app.js. level: the heading level of the trail's name. extra: HTML placed last in the row. @@ -165,6 +165,8 @@ def entry(rec, *, level=3, extra="", routes_list=False, hidden=False, eager=Fals after the others on the line of facts (a page that compares a few trails). by(rec) -> HTML: the row's author line in place of "Route by" (an author's page, where it names only the others a route is credited to); "" for none. + here: 0 for a trail wholly in the place a place page is about, 1 for one that lies elsewhere too + (data-here, the order that page opens in; see results()). The Save star follows the name in the markup (so it is the next stop for the keyboard) but is drawn under the logo, out of the row's flow (style.css @@ -206,6 +208,8 @@ def entry(rec, *, level=3, extra="", routes_list=False, hidden=False, eager=Fals lead_html = "" if rank is not None: attrs += f' data-rank="{rank}"' + if here is not None: + attrs += f' data-here="{here}"' if lead: no = f'No. {rank} ' if rank is not None else "" lead_html = (f'\n
{esc(lead[0])}
{no}' @@ -481,11 +485,15 @@ def list_head(sort_key="name"): SAVED_ORDER = ("saved", "Order saved") -def sort_select(default_sort="name", saved=False, ranked=""): +HERE_ORDER = "here" + + +def sort_select(default_sort="name", saved=False, ranked="", wholly=None): """The one sort control of every list of trails, with the page's default order selected. Hidden without JavaScript (style.css): it cannot work then, and the HTML is already in the default order. - saved: the Saved page's list, which opens in the order saved.""" + saved: the Saved page's list, which opens in the order saved. + wholly: a place page's list, which opens with the trails wholly in the place first (results()).""" sorts = facets.SORTS if saved: sorts = (SAVED_ORDER,) + tuple(sorts) @@ -493,6 +501,9 @@ def sort_select(default_sort="name", saved=False, ranked=""): elif ranked: sorts = (("rank", f"Rank: {ranked}"),) + tuple(sorts) default_sort = "rank" + elif wholly: + sorts = ((HERE_ORDER, "Wholly here first, then A to Z"),) + tuple(sorts) + default_sort = HERE_ORDER else: default_sort = facets.normalize_sort(default_sort) options = "".join( @@ -518,7 +529,7 @@ 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, every=False): + ranked="", lead=None, more=None, tools=True, by=None, every=False, wholly=None): """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 @@ -548,12 +559,21 @@ def results(recs=None, *, finder=False, groups=None, routes_list=False, default_ that leads each row's line of facts (the ranked figure, or one a page compares). more(rec) -> [(label, HTML)]: further facts for each row (entry()). tools: False for a short list inside a page that has its own (no count and no sort control). + + wholly(rec) -> bool: a place page's test for a trail that lies wholly in the place. The page opens + with those first, then the trails that lie elsewhere too, each group A to Z (data-here, and a first + sort option that app.js and this agree on); the other orders stay as everywhere. """ default_sort = facets.normalize_sort(default_sort) if groups is None: groups = [(None, recs, None)] - groups = [(heading, list(items) if ranked else facets.sort_records(list(items), default_sort), extra_fn) - for heading, items, extra_fn in groups] + if wholly: + default_sort = "name" + groups = [(heading, sorted(items, key=lambda r: (not wholly(r), sort_name(r))), extra_fn) + for heading, items, extra_fn in groups] + else: + groups = [(heading, list(items) if ranked else facets.sort_records(list(items), default_sort), extra_fn) + for heading, items, extra_fn in groups] total = sum(len(g[1]) for g in groups) shown = [r for g in groups for r in g[1]] only_routes = bool(shown) and all(facets.kind(r) == "route" for r in shown) @@ -567,7 +587,8 @@ def results(recs=None, *, finder=False, groups=None, routes_list=False, default_ routes_list=routes_list, hidden=saved, eager=not saved and seen + i < EAGER_ROWS, lead=lead(r) if lead else None, more=more(r) if more else (), - rank=seen + i + 1 if ranked else None, by=by) for i, r in enumerate(items)) + rank=seen + i + 1 if ranked else None, by=by, + here=(0 if wholly(r) else 1) if wholly else None) for i, r in enumerate(items)) seen += len(items) if isinstance(heading, tuple): heading, intro = heading @@ -593,8 +614,8 @@ def results(recs=None, *, finder=False, groups=None, routes_list=False, default_ empty = "" if not tools: return Markup(f'
{lists}
') - tools = sort_select(default_sort, saved=saved, ranked=ranked) - dflt = SAVED_ORDER[0] if saved else "rank" if ranked else default_sort + tools = sort_select(default_sort, saved=saved, ranked=ranked, wholly=wholly) + dflt = SAVED_ORDER[0] if saved else "rank" if ranked else HERE_ORDER if wholly else default_sort finder_attr = " data-finder" if finder else "" return Markup(f"""
diff --git a/web/olt/regions.py b/web/olt/regions.py index 2b7c7d4..6b54650 100644 --- a/web/olt/regions.py +++ b/web/olt/regions.py @@ -40,6 +40,16 @@ def group_box(g, by_slug): return bounds.union([k for k in keys if k.lower() in by_slug]) +def wholly_in(recs, keys): + """A test for a trail that lies wholly in a place: every state and province in its record is one + of keys (a state's own key, or the keys of a part of the country). A trail that names all of Canada + is not in any one place. None when the trails are all of one kind, so the page keeps plain A to Z.""" + keys = set(keys) + def test(rec): + return bool(facets.place_keys(rec)) and all(k in keys for k in facets.place_keys(rec)) + return test if len({test(r) for r in recs}) > 1 else None + + def group_records(records, group): return [r for r in records if group in facets.place_groups(r)] @@ -166,7 +176,7 @@ def group_page(g, records, site):
- {home.browse_view(home.listing(recs, top=2, where="g:" + g), home.overview_map(recs, f"Map of the trails in {name}", place=group_box(g, by_slug)), + {home.browse_view(home.listing(recs, top=2, where="g:" + g, wholly=wholly_in(recs, keys)), home.overview_map(recs, f"Map of the trails in {name}", place=group_box(g, by_slug)), about=f"{summary.facts(recs, records, place=(name, keys))}{summary.details(recs)}", about_title=f"About the trails in {name}")} {nav}
""" @@ -219,7 +229,7 @@ def region_page(slug, records, site, facet_pages=()):
- {home.browse_view(home.listing(recs, top=2, where=""), home.overview_map(recs, f"Map of the trails in {info['name']}", place=bounds.place_box(key)), + {home.browse_view(home.listing(recs, top=2, where="", wholly=wholly_in(recs, [key])), home.overview_map(recs, f"Map of the trails in {info['name']}", place=bounds.place_box(key)), about=f"{summary.facts(recs, records, place=(info['name'], [key]))}{summary.details(recs)}", about_title=f"About the trails in {info['name']}")} {nav} diff --git a/web/tests/test_place_order.py b/web/tests/test_place_order.py new file mode 100644 index 0000000..edb89b0 --- /dev/null +++ b/web/tests/test_place_order.py @@ -0,0 +1,81 @@ +"""Place and region pages open with the trails wholly in the place first (regions.wholly_in).""" +import copy +import os +import re +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) + +from olt import facets, home, records, regions, site # noqa: E402 + + +def row_ids(html): + return re.findall(r'
  • ]*data-id="([^"]+)"', str(html)) + + +class PlaceOrderTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.records = copy.deepcopy(records.load_records(ROOT)) + cls.site = site.load() + cls.by_slug, _ = regions.collect_regions(cls.records) + + def test_utah_leads_with_trails_wholly_in_utah(self): + ids = row_ids(regions.region_page("us-ut", self.records, self.site)[2]) + by_id = {r["id"]: r for r in self.records} + wholly = [i for i in ids if set(facets.place_keys(by_id[i])) == {"US-UT"}] + self.assertTrue(wholly and len(wholly) < len(ids)) + self.assertEqual(ids[:len(wholly)], wholly) + self.assertEqual(wholly, sorted(wholly, key=lambda i: facets.sort_name(by_id[i]))) + rest = ids[len(wholly):] + self.assertIn("american-discovery-trail", rest) + self.assertEqual(rest, sorted(rest, key=lambda i: facets.sort_name(by_id[i]))) + + def test_rows_carry_the_tier_and_the_select_opens_on_it(self): + html = str(regions.region_page("us-ut", self.records, self.site)[2]) + self.assertIn('data-default-sort="here"', html) + self.assertIn('', html) + tiers = re.findall(r'data-id="([^"]+)"[^>]* data-here="(\d)"', html) + self.assertEqual({t for _, t in tiers}, {"0", "1"}) + self.assertEqual([t for _, t in tiers], sorted(t for _, t in tiers)) + + def test_region_pages_use_their_own_places(self): + g = "mountain-west" + html = regions.group_page(g, self.records, self.site)[2] + ids = row_ids(html) + keys = set(next(k for x, _, k in facets.PLACE_GROUPS if x == g)) + by_id = {r["id"]: r for r in self.records} + tier = [0 if set(facets.place_keys(by_id[i])) <= keys else 1 for i in ids] + self.assertEqual(tier, sorted(tier)) + self.assertIn(1, tier) + + def test_a_page_whose_trails_are_all_of_one_kind_keeps_plain_order(self): + recs = [r for r in self.records if facets.place_keys(r) == ["US-UT"]] + self.assertIsNone(regions.wholly_in(recs, ["US-UT"])) + self.assertNotIn("data-here", str(home.results(recs))) + + def test_the_home_page_and_other_lists_are_unchanged(self): + html = str(home.results(self.records, every=True)) + self.assertNotIn("data-here", html) + self.assertIn('data-default-sort="name"', html) + + def test_across_canada_is_not_wholly_in_one_province(self): + test = regions.wholly_in(self.records, ["CA-ON"]) + self.assertIsNotNone(test) + for r in self.records: + if "CA-*" in facets.place_keys(r): + self.assertFalse(test(r)) + + def test_the_script_orders_here_before_name(self): + js = open(os.path.join(WEB, "assets", "app.js"), encoding="utf-8").read() + self.assertIn("SORT_KEYS.here = 1", js) + self.assertIn("if (key === 'here') return cmpNum(Number(a.dataset.here || 0)", js) + + +if __name__ == "__main__": + unittest.main()