Table to Contents widget

I'd like to create a widget that will dynamically create a table of contents based on the content itself. For starters we can just enumerate all h1 - h6 elements and list them in a nested bullet point at the top via a [[toc]] directive. But ideally we could offer a series of custom selectors that generate the content based on some other schema.