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

tweak: condtional toc #547

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
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
4 changes: 3 additions & 1 deletion gatsby-config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
require("ts-node").register({ transpileOnly: true });

const ifCondition = require("./gatsby/plugin/if-condition");

const docs = require("./docs/docs.json");

module.exports = {
Expand Down Expand Up @@ -99,7 +101,7 @@ module.exports = {
extensions: [`.mdx`, `.md`],
// https://github.com/gatsbyjs/gatsby/issues/21866#issuecomment-1063668178
// Add katex support
remarkPlugins: [require("remark-math")],
remarkPlugins: [require("remark-math"), ifCondition],
rehypePlugins: [[require("rehype-katex"), { strict: "ignore" }]],
gatsbyRemarkPlugins: [
{
Expand Down
10 changes: 7 additions & 3 deletions gatsby-node.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
require("ts-node").register({ transpileOnly: true });

const path = require("path");

const {
createDocs,
createDocHome,
Expand All @@ -10,6 +8,9 @@ const {
create404,
} = require("./gatsby/create-pages");
const { createExtraType } = require("./gatsby/create-types");
const {
createConditionalToc,
} = require("./gatsby/plugin/if-condition/create-conditional-toc");

exports.createPages = async ({ graphql, actions }) => {
await createDocHome({ graphql, actions });
Expand All @@ -23,4 +24,7 @@ exports.createPages = async ({ graphql, actions }) => {
create404({ actions });
};

exports.createSchemaCustomization = createExtraType;
exports.createSchemaCustomization = (options) => {
createExtraType(options);
createConditionalToc(options);
};
163 changes: 163 additions & 0 deletions gatsby/plugin/if-condition/create-conditional-toc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
import { CLOSE_IF_REGEX, getPageType, OPEN_IF_REGEX } from "./utils";

const visit = require(`unist-util-visit`);
const genMDX = require("gatsby-plugin-mdx/utils/gen-mdx");
const defaultOptions = require("gatsby-plugin-mdx/utils/default-options");
const generateTOC = require(`mdast-util-toc`);

export const createConditionalToc = ({
store,
pathPrefix,
getNode,
getNodes,
cache,
reporter,
actions,
schema,
...helpers
}) => {
const options = defaultOptions({});
const { createTypes } = actions;
const pendingPromises = new WeakMap();
const processMDX = ({ node }) => {
let promise = pendingPromises.get(node);
if (!promise) {
promise = genMDX({
node,
options,
store,
pathPrefix,
getNode,
getNodes,
cache,
reporter,
actions,
schema,
...helpers,
});
pendingPromises.set(node, promise);
promise.then(() => {
pendingPromises.delete(node);
});
}
return promise;
};

const tocType = schema.buildObjectType({
name: `Mdx`,
fields: {
toc: {
type: `JSON`,
args: {
maxDepth: {
type: `Int`,
default: 6,
},
},
async resolve(mdxNode, { maxDepth }) {
const { mdast } = await processMDX({ node: mdxNode });
const toc = generateTOC(mdast, { maxDepth });

let isConditional = false;
const shouldDeleteHeadings = [];
const filePath = mdxNode.fileAbsolutePath;
visit(mdast, (node) => {
const openMatch = OPEN_IF_REGEX.exec(node.value);
const closeMatch = CLOSE_IF_REGEX.exec(node.value);

if (openMatch) {
const platform = openMatch[1];
const shouldRender = platform === getPageType(filePath);

if (!shouldRender) {
isConditional = true;
}
}
if (closeMatch) {
isConditional = false;
}

if (isConditional && node.type === "heading") {
shouldDeleteHeadings.push(node.children[0].value);
}
});

const items = getItems(toc.map, {});
filterItems(items, shouldDeleteHeadings);
return items;
},
},
},
interfaces: [`Node`],
extensions: {
childOf: {
mimeTypes: options.mediaTypes,
},
},
});

createTypes([tocType]);
};

// parse mdast-utils-toc object to JSON object:
//
// {"items": [{
// "url": "#something-if",
// "title": "Something if",
// "items": [
// {
// "url": "#something-else",
// "title": "Something else"
// },
// {
// "url": "#something-elsefi",
// "title": "Something elsefi"
// }
// ]},
// {
// "url": "#something-iffi",
// "title": "Something iffi"
// }]}
//
// TODO: fully test it with different options, tight=True
//
function getItems(node, current) {
if (!node) {
return {};
} else if (node.type === `paragraph`) {
visit(node, (item) => {
if (item.type === `link`) {
current.url = item.url;
}
if (item.type === `text`) {
current.title = item.value;
}
});
return current;
} else {
if (node.type === `list`) {
current.items = node.children.map((i) => getItems(i, {}));
return current;
} else if (node.type === `listItem`) {
const heading = getItems(node.children[0], {});
if (node.children.length > 1) {
getItems(node.children[1], heading);
}
return heading;
}
}
return {};
}

function filterItems(data, filters) {
if (!data || !data.items) {
return;
}

data.items.forEach((it) => {
if (!!it.items) {
filterItems(it, filters);
}
});
data.items = data.items.filter((it) => !filters.includes(it.title));
}
34 changes: 34 additions & 0 deletions gatsby/plugin/if-condition/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import visit from "unist-util-visit";
import { CLOSE_IF_REGEX, getPageType, OPEN_IF_REGEX } from "./utils";
const remove = require("unist-util-remove");

module.exports = function () {
return (tree, file) => {
let isConditional = false;
const shoudDeleteNodes = [];
const filePath = file.path || (file.history && file.history[0]);

visit(tree, (node, index, parent) => {
const openMatch = OPEN_IF_REGEX.exec(node.value);
const closeMatch = CLOSE_IF_REGEX.exec(node.value);

if (openMatch) {
const platform = openMatch[1];
const shouldRender = platform === getPageType(filePath);

if (!shouldRender) {
isConditional = true;
}
}
if (closeMatch) {
isConditional = false;
}

if (openMatch || closeMatch || isConditional) {
shoudDeleteNodes.push(node);
}
});

shoudDeleteNodes.forEach((n) => remove(tree, n));
};
};
3 changes: 3 additions & 0 deletions gatsby/plugin/if-condition/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"version": "0.0.1"
}
11 changes: 11 additions & 0 deletions gatsby/plugin/if-condition/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export const getPageType = (filePath) => {
if (filePath.includes("/tidb/")) {
return "tidb";
}
if (filePath.includes("/tidbcloud/") || filePath.endsWith("/tidbcloud")) {
return "tidbcloud";
}
};

export const OPEN_IF_REGEX = /<IF platform="(.+?)">/;
export const CLOSE_IF_REGEX = /<\/IF>/;
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
"axios": "^0.24.0",
"clsx": "^1.1.1",
"copy-to-clipboard": "^3.3.1",
"gatsby": "^4.4.0",
"gatsby": "^4.7.0",
"gatsby-plugin-google-analytics": "^4.12.1",
"gatsby-plugin-google-tagmanager": "^4.12.1",
"gatsby-plugin-material-ui": "^4.0.2",
Expand Down
12 changes: 7 additions & 5 deletions src/templates/DocTemplate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ interface DocTemplateProps {
frontmatter: FrontMatter;
body: string;
tableOfContents: TableOfContent;
toc: TableOfContent;
};
navigation?: {
navigation: RepoNav;
Expand All @@ -66,18 +67,18 @@ export default function DocTemplate({
data,
}: DocTemplateProps) {
const {
mdx: { frontmatter, tableOfContents, body },
mdx: { frontmatter, body, toc },
navigation: originNav,
} = data;

const navigation = originNav ? originNav.navigation : [];

const tocData: TableOfContent[] | undefined = React.useMemo(() => {
if (tableOfContents.items?.length === 1) {
return tableOfContents.items![0].items;
if (toc?.items?.length === 1) {
return toc.items![0].items;
}
return tableOfContents.items || [];
}, [tableOfContents.items]);
return toc?.items || [];
}, [toc?.items]);

const stableBranch = getStable(pathConfig.repo);

Expand Down Expand Up @@ -300,6 +301,7 @@ export const query = graphql`
}
body
tableOfContents
toc
}

navigation: mdx(slug: { eq: $navUrl }) {
Expand Down
Loading