Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stable sort for left nav #374

Merged
merged 1 commit into from
Oct 23, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 21 additions & 8 deletions lib/govuk_tech_docs/table_of_contents/helpers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,27 @@ def single_page_table_of_contents(html, url: "", max_level: nil)
output
end

# Items with a weight appear first, in weight order
# if items have equal weight, they stay in the order they appeared (stable sort)
# Items without a weight appear after, sorted stably in the order that they are
# present in the resource list
def sort_resources_stably(resources)
resources
.each.with_index
.sort_by { |r, index| [r.data.weight ? 0 : 1, r.data.weight || 0, index] }
.map(&:first)
.to_a
end

def select_top_level_html_files(resources)
resources
.select { |r| r.path.end_with?(".html") && (r.parent.nil? || r.parent.url == "/") }
end

def multi_page_table_of_contents(resources, current_page, config, current_page_html = nil)
# Only parse top level html files
# Sorted by weight frontmatter
resources = resources
.select { |r| r.path.end_with?(".html") && (r.parent.nil? || r.parent.url == "/") }
.sort_by { |r| [r.data.weight ? 0 : 1, r.data.weight || 0] }
resources = sort_resources_stably(
select_top_level_html_files(resources),
)

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

def render_page_tree(resources, current_page, config, current_page_html)
# Sort by weight frontmatter
resources = resources
.sort_by { |r| [r.data.weight ? 0 : 1, r.data.weight || 0] }
resources = sort_resources_stably(resources)

output = "<ul>\n"
resources.each do |resource|
Expand Down