Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Determines order of nodes for display. display_order is nullable and has
- // higher priority over title
- const compareDisplayOrder = (a, b) => {
- const a_displayOrder = a.frontmatter.display_order
- const b_displayOrder = b.frontmatter.display_order
- if (a_displayOrder === b_displayOrder) {
- const a_title = a.frontmatter.title
- const b_title = b.frontmatter.title
- if (a_title > b_title) {
- return 1
- }
- if (a_title < b_title) {
- return -1
- }
- }
- if (a_displayOrder === null) {
- return 1
- }
- if (b_displayOrder === null) {
- return -1
- }
- if (a_displayOrder > b_displayOrder) {
- return 1
- }
- if (a_displayOrder < b_displayOrder) {
- return -1
- }
- return 0
- }
- const buildNavigationTree = edges => {
- const navigationTree = {}
- let currentBranch
- for (const edge of edges) {
- // resets to top of tree
- currentBranch = navigationTree
- // create tree based off each directory segment in slug for each node
- for (const slugSegment of edge.node.fields.slug.split("/")) {
- if (slugSegment !== "") {
- if (!currentBranch.children) {
- currentBranch.children = []
- }
- let currentBranchChildIndexForSlugSegment = currentBranch.children.findIndex(
- child => child.slugSegment === slugSegment
- )
- // if currentBranch does not have a child matching the current
- // slugSegment, create a new branch
- if (currentBranchChildIndexForSlugSegment === -1) {
- edge.node.slugSegment = slugSegment
- currentBranch.children.push(edge.node)
- currentBranchChildIndexForSlugSegment = currentBranch.children.length - 1
- }
- // change currentBranch to the branch we either just found or created
- currentBranch = currentBranch.children[currentBranchChildIndexForSlugSegment]
- }
- }
- }
- // remove root-level children property as it is unnecessary
- return navigationTree.children
- }
- const sortNavigationTree = navigationTree => {
- navigationTree.sort(compareDisplayOrder)
- for (let i = 0; i < navigationTree.length; i++) {
- // iterates through each node on current level and recursively runs for all
- // children on those nodes until each node and all their children are sorted
- if (navigationTree[i].children instanceof Array) {
- sortNavigationTree(navigationTree[i].children)
- }
- }
- return navigationTree
- }
- const data = useStaticQuery(graphql`
- query {
- allMarkdownRemark {
- edges {
- node {
- id
- frontmatter {
- title
- display_order
- }
- fields {
- slug
- }
- }
- }
- }
- }
- `)
- let navigationTree = buildNavigationTree(data.allMarkdownRemark.edges)
- navigationTree = sortNavigationTree(navigationTree)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement