Skip to content

Commit d53ea38

Browse files
authored
Merge pull request #374 from alphagov/stable-sort-left-nav
Stable sort for left nav
2 parents cb5aea0 + 8b7e5ba commit d53ea38

File tree

1 file changed

+21
-8
lines changed

1 file changed

+21
-8
lines changed

lib/govuk_tech_docs/table_of_contents/helpers.rb

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,27 @@ def single_page_table_of_contents(html, url: "", max_level: nil)
1818
output
1919
end
2020

21+
# Items with a weight appear first, in weight order
22+
# if items have equal weight, they stay in the order they appeared (stable sort)
23+
# Items without a weight appear after, sorted stably in the order that they are
24+
# present in the resource list
25+
def sort_resources_stably(resources)
26+
resources
27+
.each.with_index
28+
.sort_by { |r, index| [r.data.weight ? 0 : 1, r.data.weight || 0, index] }
29+
.map(&:first)
30+
.to_a
31+
end
32+
33+
def select_top_level_html_files(resources)
34+
resources
35+
.select { |r| r.path.end_with?(".html") && (r.parent.nil? || r.parent.url == "/") }
36+
end
37+
2138
def multi_page_table_of_contents(resources, current_page, config, current_page_html = nil)
22-
# Only parse top level html files
23-
# Sorted by weight frontmatter
24-
resources = resources
25-
.select { |r| r.path.end_with?(".html") && (r.parent.nil? || r.parent.url == "/") }
26-
.sort_by { |r| [r.data.weight ? 0 : 1, r.data.weight || 0] }
39+
resources = sort_resources_stably(
40+
select_top_level_html_files(resources),
41+
)
2742

2843
render_page_tree(resources, current_page, config, current_page_html)
2944
end
@@ -40,9 +55,7 @@ def list_items_from_headings(html, url: "", max_level: nil)
4055
end
4156

4257
def render_page_tree(resources, current_page, config, current_page_html)
43-
# Sort by weight frontmatter
44-
resources = resources
45-
.sort_by { |r| [r.data.weight ? 0 : 1, r.data.weight || 0] }
58+
resources = sort_resources_stably(resources)
4659

4760
output = "<ul>\n"
4861
resources.each do |resource|

0 commit comments

Comments
 (0)