Skip to content

Commit

Permalink
feat: 🎸 set depth attribute in mdastToFlat()
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Mar 3, 2019
1 parent d75bc86 commit 0f5eca7
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/__tests__/mdastToFlat.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,14 @@ describe('structure', () => {
});
});

it('root node should have a depth attribute', () => {
const parser = create();
const mdast = parser.tokenizeBlock('foo');
const flat = mdastToFlat(mdast!);

expect(flat.nodes[0].depth).toBe(0);
});

it('adds titles to contents list', () => {
const parser = create();
const mdast = parser.tokenizeBlock('# Title\n' + '\n' + '## Subtitle\n');
Expand Down
5 changes: 5 additions & 0 deletions src/mdastToFlat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export const mdastToFlat: MdastToFlat = (mdast) => {
if (mdast) {
traverse(mdast, 0);

// Process references.
let footnoteCounter = 0;
for (const node of nodes) {
if ((node.type === 'footnoteReference') || (node.type === 'imageReference')) {
Expand All @@ -65,6 +66,10 @@ export const mdastToFlat: MdastToFlat = (mdast) => {
}
}
}

// Process root node.
const root = doc.nodes[0];
root.depth = 0;
}

return doc;
Expand Down
2 changes: 2 additions & 0 deletions src/replace.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {Flat} from './types';
import {findRoot} from './findRoot';

export const replace = (into: Flat, at: number, what: Flat): Flat => {
const mergeIdx = into.nodes.length;
Expand Down Expand Up @@ -33,6 +34,7 @@ export const replace = (into: Flat, at: number, what: Flat): Flat => {
merged.nodes.push(newNode);
}
merged.nodes[mergeIdx].parent = at;
merged.nodes[mergeIdx].depth = (into.nodes[findRoot(into, at)].depth || 0) + 1;

// MERGE METADATA.
for (const idx of what.contents) {
Expand Down
4 changes: 4 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ export interface FlatFootnotes {
export type TNode = (IRoot | TAnyToken) & {
idx: number;
parent: number;
/**
* Root nodes have `depth` key, which tracks how deeply they have been merged.
*/
depth?: number;
children?: number[];
};

Expand Down

0 comments on commit 0f5eca7

Please sign in to comment.