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

First pass at a Table of Contents generator from markdown #8348

Draft
wants to merge 6 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
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
143 changes: 143 additions & 0 deletions app/bin/toc.dart
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);
}
2 changes: 1 addition & 1 deletion app/lib/frontend/static_files.dart
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ void registerStaticFileCacheForTest(StaticFileCache cache) {

/// Returns the path of the `app/` directory.
String resolveAppDir() {
if (Directory.current.path.endsWith('/app') &&
if (Directory.current.path.endsWith('app') &&
Directory('${Directory.current.path}/../static').existsSync()) {
return Directory.current.path;
}
Expand Down
1 change: 1 addition & 0 deletions app/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ dependencies:
ulid: '2.0.1'
tar: '2.0.0'
api_builder:
simple_mustache: ^2.1.0
Copy link
Member

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.

Copy link
Author

@Levi-Lesches Levi-Lesches Dec 4, 2024

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


dev_dependencies:
build_runner: '^2.0.0'
Expand Down
1 change: 1 addition & 0 deletions app/toc_experiment/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
index.html
51 changes: 51 additions & 0 deletions app/toc_experiment/md_toc.template
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&amp;family=Google+Sans+Display:wght@400&amp;family=Google+Sans+Text:wght@400;500;700&amp;family=Google+Sans+Mono:wght@400;700&amp;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>
Loading