Skip to content

Commit

Permalink
fix: Correctly configure remark-toc
Browse files Browse the repository at this point in the history
  • Loading branch information
tgreyuk committed Jan 11, 2024
1 parent 7073443 commit 978be7a
Show file tree
Hide file tree
Showing 21 changed files with 168 additions and 97 deletions.
9 changes: 7 additions & 2 deletions dev-packages/prebuild-options/tasks/generate-docs.ts
Expand Up @@ -114,7 +114,10 @@ export async function generateDocs(docsConfig: DocsConfig) {
});
}

if (option.type === ParameterType.Mixed && option.defaultValue) {
if (
option.type === ParameterType.Mixed &&
option.defaultValue?.length
) {
out.push('Below is the full list of keys and default values:');
}

Expand Down Expand Up @@ -165,7 +168,9 @@ function getType(option: any) {
}

if (option.type === ParameterType.Mixed && option.defaultValue) {
return 'Accepts a key/value object (see example).';
return Array.isArray(option.defaultValue)
? 'Accepts an array (see example)'
: 'Accepts a key/value object (see example).';
}

if (option.type === ParameterType.Map && option.map) {
Expand Down
2 changes: 0 additions & 2 deletions docs/pages/options.mdx
Expand Up @@ -390,8 +390,6 @@ Keys are categorised with the following namespace conventions:

Only keys that require translation need to be added to the object.

Below is the full list of keys and default values:


```json filename="typedoc.json"
{
Expand Down
2 changes: 1 addition & 1 deletion docs/pages/utilities/frontmatter/quick-start.mdx
Expand Up @@ -16,6 +16,6 @@ npm install typedoc-plugin-frontmatter@next --save-dev

```json filename="typedoc.json"
{
"plugin": ["typedoc-plugin-frontmatter"]
"plugin": ["typedoc-plugin-markdown", "typedoc-plugin-frontmatter"]
}
```
3 changes: 2 additions & 1 deletion docs/pages/utilities/remark/_meta.json
@@ -1,4 +1,5 @@
{
"quick-start": "",
"options": ""
"options": "",
"suggested-plugins": ""
}
21 changes: 18 additions & 3 deletions docs/pages/utilities/remark/options.mdx
Expand Up @@ -6,16 +6,31 @@ These are the additional options that can be added to the TypeDoc configuration.

## remarkPlugins

<Callout>An array of remark plugins.</Callout>
<Callout>An array of remark plugin names.</Callout>

>
> Accepts an array (see example)

Each required plugin should be individually installed.

Please note options can be passed to plugins using the format:

```json
{['plugin-name', { pluginOption:true }]}
```


```json filename="typedoc.json"
{
"remarkPlugins": [
"unified-prettier",
"remark-github",
"unified-prettier"
[
"remark-toc",
{
"maxDepth": 3
}
]
]
}

Expand Down
2 changes: 1 addition & 1 deletion docs/pages/utilities/remark/quick-start.mdx
Expand Up @@ -16,6 +16,6 @@ npm install typedoc-plugin-remark@next --save-dev

```json filename="typedoc.json"
{
"plugin": ["typedoc-plugin-remark"]
"plugin": ["typedoc-plugin-markdown", "typedoc-plugin-remark"]
}
```
19 changes: 19 additions & 0 deletions docs/pages/utilities/remark/suggested-plugins.mdx
@@ -0,0 +1,19 @@
# Suggested plugins

Any compatible remark plugins can be used (or you can write your own). Here are some that might be useful.

## [unified-prettier](https://github.com/remcohaszing/unified-prettier)

Improving code formatting by parsing with [Prettier](https://prettier.io/):

- Produces a consistent format.
- Removes unnecessary escape characters.
- Formats code blocks inside comment fenced blocks.

## [remark-github](https://github.com/remarkjs/remark-github)

- Links references to commits, issues, and users in the same way that GitHub does in comments.

## [remark-toc](https://github.com/remarkjs/remark-toc)

- Adds inline table of contents to pages.
3 changes: 0 additions & 3 deletions packages/typedoc-plugin-frontmatter/src/index.ts
Expand Up @@ -10,9 +10,6 @@ import * as options from './options/declarations';
import { getFrontmatterTags } from './tags';

export function load(app: Application) {
/**
* add options x
*/
Object.entries(options).forEach(([name, option]) => {
app.options.addDeclaration({
name,
Expand Down
2 changes: 1 addition & 1 deletion packages/typedoc-plugin-remark/package.json
@@ -1,7 +1,7 @@
{
"name": "typedoc-plugin-remark",
"version": "0.0.1-next.0",
"description": "A plugin for TypeDoc that enables additional markdown transformations with remark.",
"description": "A plugin for TypeDoc that enables additional markdown transformations with remark plugins.",
"main": "./dist/index.js",
"files": [
"dist/"
Expand Down
68 changes: 43 additions & 25 deletions packages/typedoc-plugin-remark/src/index.ts
Expand Up @@ -17,34 +17,52 @@ export function load(app: Application) {
});

app.renderer.on(MarkdownPageEvent.END, (event: MarkdownPageEvent) => {
const isModulesOnly = (
event?.model as DeclarationReflection
).children?.every((child) => child.kindOf(ReflectionKind.Module));
const outputFileStrategy = app.options.getValue('outputFileStrategy');
const remarkPlugins = app.options.getValue('remarkPlugins') as [];
const remarkPluginsNames = remarkPlugins.map((plugin) =>
Array.isArray(plugin) ? plugin[0] : plugin,
) as string[];

const kindsWithToc = [
ReflectionKind.Namespace,
ReflectionKind.Class,
ReflectionKind.Enum,
ReflectionKind.Interface,
];
if (remarkPluginsNames.includes('remark-toc')) {
const tocPluginIndex = remarkPluginsNames.findIndex(
(name) => name === 'remark-toc',
);
const tocPlugin = remarkPlugins[tocPluginIndex];

const options = tocPlugin[1];

const isModulesOnly = (
event?.model as DeclarationReflection
).children?.every((child) => child.kindOf(ReflectionKind.Module));
const outputFileStrategy = app.options.getValue('outputFileStrategy');

const kindsWithToc = [
ReflectionKind.Namespace,
ReflectionKind.Class,
ReflectionKind.Enum,
ReflectionKind.Interface,
];

if (outputFileStrategy === OutputFileStrategy.Modules) {
kindsWithToc.push(ReflectionKind.Module);
if (!isModulesOnly) {
kindsWithToc.push(ReflectionKind.Project);
if (outputFileStrategy === OutputFileStrategy.Modules) {
kindsWithToc.push(ReflectionKind.Module);
if (!isModulesOnly) {
kindsWithToc.push(ReflectionKind.Project);
}
}
}

if (kindsWithToc.includes(event.model?.kind)) {
const contents = event.contents;
const contentToLines = contents?.split('\n');
const firstHeadingIndex = contentToLines?.findIndex((line) =>
line.startsWith('##'),
);
if (firstHeadingIndex && firstHeadingIndex > 0) {
contentToLines?.splice(firstHeadingIndex, 0, `\n\n## Contents\n\n`);
event.contents = contentToLines?.join('\n');
if (kindsWithToc.includes(event.model?.kind)) {
const contents = event.contents;
const contentToLines = contents?.split('\n');
const firstHeadingIndex = contentToLines?.findIndex((line) =>
line.startsWith('##'),
);
if (firstHeadingIndex && firstHeadingIndex > 0) {
contentToLines?.splice(
firstHeadingIndex,
0,
`\n\n## ${(options as any)?.heading || 'Contents'}\n\n`,
);
event.contents = contentToLines?.join('\n');
}
}
}
});
Expand All @@ -62,7 +80,7 @@ export function load(app: Application) {
if (remarkPlugins.length) {
app.logger.info(
`Output parsed using remark plugin(s) [${remarkPlugins
.map((plugin) => `"${plugin}"`)
.map((plugin) => `"${Array.isArray(plugin) ? plugin[0] : plugin}"`)
.join(', ')}]`,
);
}
Expand Down
18 changes: 16 additions & 2 deletions packages/typedoc-plugin-remark/src/options/declarations.ts
Expand Up @@ -2,9 +2,23 @@ import { DeclarationOption, ParameterType } from 'typedoc';

/**
*
* @example ["remark-github", "unified-prettier"]
* Each required plugin should be individually installed.
*
* Please note options can be passed to plugins using the format:
*
* ```json
* {['plugin-name', { pluginOption:true }]}
* ```
*
* @example ["unified-prettier","remark-github", ["remark-toc", { "maxDepth": 3 }] ]
*/
export const remarkPlugins: Partial<DeclarationOption> = {
help: 'An array of remark plugins.',
help: 'An array of remark plugin names.',
type: ParameterType.Mixed,
defaultValue: [],
validate(value) {
if (!Array.isArray(value)) {
throw new Error('remarkPlugins must be an array.');
}
},
};
8 changes: 5 additions & 3 deletions packages/typedoc-plugin-remark/src/options/models.ts
@@ -1,13 +1,15 @@
// THIS FILE IS AUTO GENERATED FROM THE OPTIONS CONFIG. DO NOT EDIT DIRECTLY.

false;
import { ManuallyValidatedOption } from 'typedoc';

declare module 'typedoc' {
export interface TypeDocOptionMap {
remarkPlugins: any;
remarkPlugins: ManuallyValidatedOption<RemarkPlugins>;
}
}

export interface PluginOptions {
remarkPlugins: any;
remarkPlugins: ManuallyValidatedOption<RemarkPlugins>;
}

export interface RemarkPlugins {}
3 changes: 1 addition & 2 deletions packages/typedoc-plugin-remark/src/remark.cjs
Expand Up @@ -8,8 +8,7 @@ module.exports = {
const { remark } = await import('remark');
const { read, writeSync } = await import('to-vfile');
const file = await read(filePath);
const processor = remark(); /*.data('settings', {})*/

const processor = remark();
if (plugins.length > 0) {
const promises = plugins.map(async (plugin) => {
return new Promise((resolve) => {
Expand Down
3 changes: 2 additions & 1 deletion packages/typedoc-plugin-remark/test/__scripts__/prepare.ts
Expand Up @@ -13,6 +13,7 @@ const fixtures = [
{ options: 'typedoc.modules.json', outDir: 'modules' },
{ options: 'typedoc.members.json', outDir: 'members' },
{ options: 'typedoc.globals.json', outDir: 'globals' },
{ options: 'typedoc.globals-notoc.json', outDir: 'globals-notoc' },
];

// write fixtures
Expand All @@ -28,7 +29,7 @@ function writeMarkdown(fixture: any) {
'-options',
`./test/${fixture.options}`,
'-logLevel',
'Info',
'Warn',
'-out',
`./test/out/${fixture.outDir}`,
],
Expand Down
Expand Up @@ -3,66 +3,45 @@
exports[`Remark should parse globals page 1`] = `
"# typedoc-plugin-remark
Comments form module comments
Thanks [**@tgrey**](https://github.com/tgrey) please see issue [#1](https://github.com/tgreyuk/typedoc-plugin-markdown/issues/1).
\`\`\`js
reallyUgly(javascript);
\`\`\`
\`\`\`css
.h1 {
color: red;
}
\`\`\`
## CustomTOC
## Contents
- [Classes](#classes)
- [SomeClass](#someclass)
- [Interfaces](#interfaces)
- [SomeInterface](#someinterface)
- [Variables](#variables)
- [\\_\\_variable_with_underscores\\_\\_](#__variable_with_underscores__)
- [someVariable](#somevariable)
- [Functions](#functions)
- [some_function()](#some_function)
## Classes
### SomeClass
#### Constructors
##### new SomeClass()
> **new SomeClass**(): [\`SomeClass\`](README.md#someclass)
## Variables
###### Returns
### someVariable
[\`SomeClass\`](README.md#someclass)
> **\`const\`** **someVariable**: \`true\` = \`true\`
#### Properties
## Functions
##### someProp
### some_function()
> **someProp**: \`string\`
> **some_function**(\`param\`): \`void\`
## Interfaces
#### Parameters
### SomeInterface
| Parameter | Type |
| :-------- | :------- |
| \`param\` | \`string\` |
#### Properties
#### Returns
##### someProp
\`void\`
"
`;

> **someProp**: \`string\`
exports[`Remark should parse globals page without toc 1`] = `
"# typedoc-plugin-remark
## Variables
### \\_\\_variable_with_underscores\\_\\_
### someVariable
> **\`const\`** **\\_\\_variable_with_underscores\\_\\_**: \`true\` = \`true\`
> **\`const\`** **someVariable**: \`true\` = \`true\`
## Functions
Expand Down
7 changes: 7 additions & 0 deletions packages/typedoc-plugin-remark/test/specs/remark.spec.ts
Expand Up @@ -45,4 +45,11 @@ describe(`Remark`, () => {
.toString();
expect(contents).toMatchSnapshot();
});

test(`should parse globals page without toc`, async () => {
const contents = fs
.readFileSync(path.join(__dirname, '../out/globals-notoc/README.md'))
.toString();
expect(contents).toMatchSnapshot();
});
});
5 changes: 0 additions & 5 deletions packages/typedoc-plugin-remark/test/typedoc.base.json
Expand Up @@ -3,11 +3,6 @@
"tsconfig": "./stubs/tsconfig.json",
"out": "./out",
"plugin": ["typedoc-plugin-markdown", "typedoc-plugin-remark"],
"remarkPlugins": [
"remark-github",
"unified-prettier",
["remark-toc", { "maxDepth": 3 }]
],
"readme": "none",
"parametersFormat": "table",
"githubPages": false,
Expand Down

0 comments on commit 978be7a

Please sign in to comment.