-
Notifications
You must be signed in to change notification settings - Fork 159
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
First pass at a Table of Contents generator from markdown #8348
Draft
Levi-Lesches
wants to merge
6
commits into
dart-lang:master
Choose a base branch
from
Levi-Lesches:toc-parser
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,143 @@ | ||
import 'dart:io' as io; | ||
|
||
import 'package:markdown/markdown.dart'; | ||
import 'package:pub_dev/frontend/dom/dom.dart' as dom; | ||
import 'package:simple_mustache/simple_mustache.dart'; | ||
|
||
const _structuralHeaderTags = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']; | ||
final currentUri = Uri(); | ||
const rootDir = './toc_experiment'; | ||
|
||
String generateFragment(String text) => BlockSyntax.generateAnchorHash( | ||
Element.text('h1', text), | ||
); | ||
|
||
/// A section of the Table of Contents | ||
class TocNode { | ||
/// What level heading this node is. | ||
/// | ||
/// This is not defined by what tag it is using, or how many `#` it has, but rather | ||
/// how many levels of nesting have occurred in the document so far. That is to say, | ||
/// | ||
/// ```md | ||
/// # Level 1 | ||
/// ### Level 2 | ||
/// ##### Level 3 | ||
/// ``` | ||
int level; | ||
|
||
/// The list of [TocNode] that are nested under this heading. | ||
List<TocNode> children; | ||
|
||
/// The title of the node, as a string. | ||
final String title; | ||
|
||
/// The parent heading for this node. | ||
TocNode? parent; | ||
|
||
TocNode({required this.level,required this.title, this.parent}) : | ||
children = []; | ||
|
||
|
||
/// Where this heading should point to on the page. | ||
Uri get href => currentUri.replace(fragment: generateFragment(title)); | ||
|
||
/// Generates a nested list of this heading and all its children. | ||
dom.Node toHtml() => dom.li( | ||
children: [ | ||
dom.a(text: title, href: href.toString()), | ||
dom.ul( | ||
children: [ | ||
for (final child in children) | ||
child.toHtml(), | ||
], | ||
), | ||
], | ||
); | ||
} | ||
|
||
List<TocNode> parse(List<Node> nodes) { | ||
final result = <TocNode>[]; | ||
TocNode? currentSection; | ||
|
||
for (final node in nodes) { | ||
if (node is! Element) continue; | ||
|
||
final currentLevel = _structuralHeaderTags.indexOf(node.tag); | ||
final isHeading = currentLevel != -1; | ||
if (!isHeading) continue; | ||
|
||
final section = TocNode(title: node.textContent, level: currentLevel); | ||
if (currentSection == null) { | ||
currentSection = section; | ||
result.add(section); | ||
continue; | ||
} | ||
|
||
var previousLevel = currentSection.level; | ||
|
||
if (currentLevel > previousLevel) { | ||
currentSection.children.add(section); | ||
section.parent = currentSection; | ||
currentSection = section; | ||
continue; | ||
} else if (currentLevel < previousLevel) { | ||
while (currentLevel < previousLevel) { | ||
currentSection = currentSection?.parent; | ||
previousLevel = currentSection!.level; | ||
} | ||
if (currentSection?.parent != null) { | ||
currentSection = currentSection!.parent; | ||
section.parent = currentSection; | ||
currentSection!.children.add(section); | ||
currentSection = section; | ||
} else { | ||
result.add(section); | ||
currentSection = section; | ||
} | ||
} else { | ||
if (currentSection.parent != null) { | ||
currentSection = currentSection.parent; | ||
section.parent = currentSection; | ||
currentSection!.children.add(section); | ||
currentSection = section; | ||
} else { | ||
result.add(section); | ||
currentSection = section; | ||
} | ||
} | ||
} | ||
return result; | ||
} | ||
|
||
dom.Node renderToc(List<TocNode> toc) => dom.ul( | ||
children: [ | ||
for (final heading in toc) | ||
heading.toHtml(), | ||
] | ||
); | ||
|
||
void main(List<String> args) { | ||
final file = io.File('$rootDir/readme.md'); | ||
final markdown = file.readAsStringSync(); | ||
final nodes = getNodes(markdown); | ||
final toc = parse(nodes); | ||
renderMarkdownWithToc(markdown, toc); | ||
} | ||
|
||
void renderMarkdownWithToc(String markdown, List<TocNode> sections) { | ||
final templateFile = io.File('$rootDir/md_toc.template'); | ||
final template = templateFile.readAsStringSync(); | ||
final readme = dom.markdown(markdown); | ||
final toc = renderToc(sections); | ||
final map = {'toc': toc.toString(), 'main': readme.toString()}; | ||
final html = Mustache(map: map).convert(template); | ||
final outputFile = io.File('$rootDir/index.html'); | ||
outputFile.writeAsStringSync(html.toString()); | ||
} | ||
|
||
List<Node> getNodes(String markdown) { | ||
final document = Document(); | ||
final lines = markdown.replaceAll('\r\n', '\n').split('\n'); | ||
return document.parseLines(lines); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
index.html |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
<html> | ||
<head> | ||
<script src="https://www.googletagmanager.com/gtm.js?id=GTM-MX6DBN9" async="async"></script> | ||
<script src="/static/hash-%%etag%%/js/gtm.js" async="async"></script> | ||
<meta charset="utf-8"/> | ||
<meta http-equiv="x-ua-compatible" content="ie=edge"/> | ||
<meta name="viewport" content="width=device-width, initial-scale=1"/> | ||
<meta name="robots" content="noindex"/> | ||
<meta name="twitter:card" content="summary"/> | ||
<meta name="twitter:site" content="@dart_lang"/> | ||
<meta name="twitter:description" content="oxygen is awesome"/> | ||
<meta name="twitter:image" content="https://pub.dev/static/hash-%%etag%%/img/pub-dev-icon-cover-image.png"/> | ||
<meta property="og:type" content="website"/> | ||
<meta property="og:site_name" content="Dart packages"/> | ||
<meta property="og:title" content="oxygen example | Dart package"/> | ||
<meta property="og:description" content="oxygen is awesome"/> | ||
<meta property="og:image" content="https://pub.dev/static/hash-%%etag%%/img/pub-dev-icon-cover-image.png"/> | ||
<title>oxygen example | Dart package</title> | ||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Google+Sans:wght@400;500;700&family=Google+Sans+Display:wght@400&family=Google+Sans+Text:wght@400;500;700&family=Google+Sans+Mono:wght@400;700&display=swap"/> | ||
<link rel="shortcut icon" href="/favicon.ico?hash=mocked_hash_985685822"/> | ||
<link rel="stylesheet" href="https://www.gstatic.com/glue/v25_0/ccb.min.css"/> | ||
<link rel="search" type="application/opensearchdescription+xml" title="Dart packages" href="/osd.xml"/> | ||
<link rel="canonical" href="https://pub.dev/packages/oxygen/example"/> | ||
<meta name="description" content="oxygen is awesome"/> | ||
<link rel="alternate" type="application/atom+xml" title="Updated Packages Feed for Pub" href="/feed.atom"/> | ||
<link rel="stylesheet" type="text/css" href="/static/hash-%%etag%%/material/bundle/styles.css"/> | ||
<link rel="stylesheet" type="text/css" href="/static/hash-%%etag%%/css/style.css"/> | ||
<script src="/static/hash-%%etag%%/material/bundle/script.min.js" defer="defer"></script> | ||
<script src="/static/hash-%%etag%%/js/script.dart.js" defer="defer"></script> | ||
<script src="https://www.gstatic.com/brandstudio/kato/cookie_choice_component/cookie_consent_bar.v3.js" defer="defer" data-autoload-cookie-consent-bar="true"></script> | ||
<meta name="pub-page-data" content="eyJwa2dEYXRhIjp7InBhY2thZ2UiOiJveHlnZW4iLCJ2ZXJzaW9uIjoiMS4yLjAiLCJsaWtlcyI6MCwiaXNEaXNjb250aW51ZWQiOmZhbHNlLCJpc0xhdGVzdCI6dHJ1ZX0sInNlc3Npb25Bd2FyZSI6ZmFsc2V9"/> | ||
<link rel="preload" href="/static/hash-%%etag%%/highlight/highlight-with-init.js" as="script"/> | ||
|
||
<style> | ||
body { | ||
display: flex; | ||
} | ||
aside { | ||
position: fixed; | ||
width: 400px | ||
} | ||
main { | ||
padding-left: 450px | ||
} | ||
</style> | ||
</head> | ||
<body> | ||
<aside>{{ toc }}</aside> | ||
<main>{{ main }}</main> | ||
</body> | ||
</html> |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
we can't pull in arbitrary dependencies.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not using this package for the parsing code, don't worry.
In the previous thread we decided not to focus on the UI elements of the parsing yet, so I didn't integrate this into the standard Pub package page, and instead make some quick-and-dirty HTML to show off the results. That's what this package is for and should not be used in the final site. For this PR, I'm just focusing on the parsing code itself