How can I automatically assign a different color to each heading?

Sure. All you need to do is replace the lines up to calculating the ratio with

  //get all level-one headings
  #let allheadings = query(heading.where(level: 1))

  #let currentheading = query(heading.where(level: 1).before(here()))

  #let ratio = currentheading.len() / allheadings.len() * 100%

This will calculate the ratio using the number of headings in the document, instead of relying on the counter whose value can be changed arbitrarily

1 Like