Skip to content

Commit

Permalink
Merge pull request #60 from empress/markdown-headers
Browse files Browse the repository at this point in the history
Add Markdown Headers to JSON:API output
  • Loading branch information
mansona authored Sep 25, 2021
2 parents e3763b9 + 5f44bf8 commit 7e5aade
Show file tree
Hide file tree
Showing 4 changed files with 675 additions and 67 deletions.
16 changes: 14 additions & 2 deletions lib/markdown-to-jsonapi.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ const showdown = require('showdown');
const _ = require('lodash');
const h2p = require('html2plaintext');
const { Serializer } = require('jsonapi-serializer');
const { JSDOM } = require('jsdom');

const supportedContentTypes = ['content', 'html', 'description'];
const supportedContentTypes = ['content', 'html', 'description', 'toc'];

class MarkDownToJsonApi extends PersistentFilter {
constructor(folder, options) {
Expand Down Expand Up @@ -63,12 +64,23 @@ class MarkDownToJsonApi extends PersistentFilter {
processString(content, relativePath) {
const front = yamlFront.loadFront(content);
const markdown = front.__content.trim();
const html = this.converter.makeHtml(markdown);

const dom = new JSDOM(html);
const headingNodes = dom.window.document.querySelectorAll('h1, h2, h3, h4, h5');

const toc = [...headingNodes].map((heading) => ({
text: heading.textContent,
depth: heading.nodeName.replace(/\D/g, ''),
id: heading.getAttribute('id'),
}));

const baseProperties = {
path: relativePath,
id: relativePath.replace(/\.(md|markdown)$/, ''),
content: markdown,
html: this.converter.makeHtml(markdown),
html,
toc,
};

const resultHash = { ...baseProperties, ...front };
Expand Down
Loading

0 comments on commit 7e5aade

Please sign in to comment.