docs(v2): Reorganize/split the guides doc sections (#3975)

* docs reorg

* refactor docs/markdown features section

* fix broken links after docs refactor
This commit is contained in:
Sébastien Lorber 2020-12-30 17:03:25 +01:00 committed by GitHub
parent a0c5177182
commit d99d53a236
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
20 changed files with 1347 additions and 1192 deletions

View file

@ -4,7 +4,7 @@ title: '📦 plugin-content-docs'
slug: '/api/plugins/@docusaurus/plugin-content-docs' slug: '/api/plugins/@docusaurus/plugin-content-docs'
--- ---
Provides the [Docs](markdown-features.mdx) functionality and is the default docs plugin for Docusaurus. Provides the [Docs](../../guides/docs/docs-introduction.md) functionality and is the default docs plugin for Docusaurus.
## Installation ## Installation
@ -133,3 +133,36 @@ module.exports = {
], ],
}; };
``` ```
## Markdown Frontmatter
Markdown documents can use the following markdown frontmmatter metadata fields, enclosed by a line `---` on either side:
- `id`: A unique document id. If this field is not present, the document's `id` will default to its file name (without the extension).
- `title`: The title of your document. If this field is not present, the document's `title` will default to its `id`.
- `hide_title`: Whether to hide the title at the top of the doc. By default it is `false`.
- `hide_table_of_contents`: Whether to hide the table of contents to the right. By default it is `false`.
- `sidebar_label`: The text shown in the document sidebar and in the next/previous button for this document. If this field is not present, the document's `sidebar_label` will default to its `title`.
- `custom_edit_url`: The URL for editing this document. If this field is not present, the document's edit URL will fall back to `editUrl` from options fields passed to `docusaurus-plugin-content-docs`.
- `keywords`: Keywords meta tag for the document page, for search engines.
- `description`: The description of your document, which will become the `<meta name="description" content="..."/>` and `<meta property="og:description" content="..."/>` in `<head>`, used by search engines. If this field is not present, it will default to the first line of the contents.
- `image`: Cover or thumbnail image that will be used when displaying the link to your post.
Example:
```yml
---
id: doc-markdown
title: Markdown Features
hide_title: false
hide_table_of_contents: false
sidebar_label: Markdown :)
custom_edit_url: https://github.com/facebook/docusaurus/edit/master/docs/api-doc-markdown.md
description: How do I find you when I cannot solve this problem
keywords:
- docs
- docusaurus
image: https://i.imgur.com/mErPwqL.png
---
My Document Markdown content
```

View file

@ -399,7 +399,7 @@ module.exports = {
:::note :::note
If you use the line highlighting Markdown syntax, you might need to specify a different highlight background color for the dark mode syntax highlighting theme. Refer to the [docs for guidance](markdown-features.mdx#line-highlighting). If you use the line highlighting Markdown syntax, you might need to specify a different highlight background color for the dark mode syntax highlighting theme. Refer to the [docs for guidance](../../guides/markdown-features/markdown-features-code-blocks.mdx#line-highlighting).
::: :::

View file

@ -4,7 +4,7 @@ title: '📦 theme-live-codeblock'
slug: '/api/themes/@docusaurus/theme-live-codeblock' slug: '/api/themes/@docusaurus/theme-live-codeblock'
--- ---
This theme provides a `@theme/CodeBlock` component that is powered by react-live. You can read more on [interactive code editor](markdown-features.mdx#interactive-code-editor) documentation. This theme provides a `@theme/CodeBlock` component that is powered by react-live. You can read more on [interactive code editor](../../guides/markdown-features/markdown-features-code-blocks.mdx#interactive-code-editor) documentation.
```bash npm2yarn ```bash npm2yarn
npm install --save @docusaurus/theme-live-codeblock npm install --save @docusaurus/theme-live-codeblock

View file

@ -0,0 +1,75 @@
---
id: create-doc
title: Create a doc
description: Create a Markdown Document
slug: /create-doc
---
Create a markdown file, `greeting.md`, and place it under the `docs` directory.
```bash
website # root directory of your site
├── docs
│   └── greeting.md
├── src
│   └── pages
├── docusaurus.config.js
├── ...
```
At the top of the file, specify `id` and `title` in the front matter, so that Docusaurus will pick them up correctly when generating your site.
```yml
---
id: greeting
title: Hello
---
## Hello from Docusaurus
Are you ready to create the documentation site for your open source project?
### Headers
will show up on the table of contents on the upper right
So that your users will know what this page is all about without scrolling down or even without reading too much.
### Only h2 and h3 will be in the toc
The headers are well-spaced so that the hierarchy is clear.
- lists will help you
- present the key points
- that you want your users to remember
- and you may nest them
- multiple times
```
This will render in the browser as follows:
import BrowserWindow from '@site/src/components/BrowserWindow';
<BrowserWindow url="http://localhost:3000">
<h2>Hello from Docusaurus</h2>
Are you ready to create the documentation site for your open source project?
<h3>Headers</h3>
will show up on the table of contents on the upper right
So that your users will know what this page is all about without scrolling down or even without reading too much.
<h3>Only h2 and h3 will be in the toc</h3>
The headers are well-spaced so that the hierarchy is clear.
- lists will help you
- present the key points
- that you want your users to remember
- and you may nest them
- multiple times
</BrowserWindow>

View file

@ -1,7 +1,8 @@
--- ---
id: docs-introduction id: introduction
title: Docs Introduction title: Docs Introduction
sidebar_label: Introduction sidebar_label: Introduction
slug: /docs-introduction
--- ---
The docs feature provides users with a way to organize Markdown files in a hierarchical format. The docs feature provides users with a way to organize Markdown files in a hierarchical format.
@ -74,6 +75,6 @@ You should delete the existing homepage at `./src/pages/index.js`, or else there
:::tip :::tip
There's also a "blog-only mode" for those who only want to use the blog feature of Docusaurus 2. You can use the same method detailed above. Follow the setup instructions on [Blog-only mode](blog.md#blog-only-mode). There's also a "blog-only mode" for those who only want to use the blog feature of Docusaurus 2. You can use the same method detailed above. Follow the setup instructions on [Blog-only mode](../../blog.md#blog-only-mode).
::: :::

View file

@ -0,0 +1,28 @@
---
id: markdown-features
title: Docs Markdown Features
description: Docusaurus Markdown features that are specific to the docs plugin
slug: /docs-markdown-features
---
Docs can use any [Markdown feature](../markdown-features/markdown-features-intro.mdx), and have a few additional Docs-specific markdown features.
## Markdown frontmatter
Markdown docs have their own [Markdown frontmatter](../../api/plugins/plugin-content-docs.md#markdown-frontmatter)
## Referencing other documents
If you want to reference another document file, you could use the name of the document you want to reference. Docusaurus will convert the file path to be the final website path (and remove the `.md`).
For example, if you are in `doc2.md` and you want to reference `doc1.md` and `folder/doc3.md`:
```md
I am referencing a [document](doc1.md). Reference to another [document in a folder](folder/doc3.md).
[Relative document](../doc2.md) referencing works as well.
```
One benefit of this approach is that the links to external files will still work if you are viewing the file on GitHub.
Another benefit, for versioned docs, is that one versioned doc will link to another doc of the exact same version.

View file

@ -1,5 +1,5 @@
--- ---
id: docs-sidebar id: sidebar
title: Sidebar title: Sidebar
slug: /sidebar slug: /sidebar
--- ---
@ -105,7 +105,7 @@ By default, the doc page the user is reading will display the sidebar that it is
For example, with the above example, when displaying the `doc2` page, the sidebar will contain the items of `secondSidebar` only. Another example of multiple sidebars is the `API` and `Docs` sections on the Docusaurus website. For example, with the above example, when displaying the `doc2` page, the sidebar will contain the items of `secondSidebar` only. Another example of multiple sidebars is the `API` and `Docs` sections on the Docusaurus website.
For more information about sidebars and how they relate to doc pages, see [Navbar doc link](./api/themes/theme-configuration.md#navbar-doc-link). For more information about sidebars and how they relate to doc pages, see [Navbar doc link](../../api/themes/theme-configuration.md#navbar-doc-link).
## Understanding sidebar items ## Understanding sidebar items

View file

@ -1,6 +1,7 @@
--- ---
id: versioning id: versioning
title: Versioning title: Versioning
slug: /versioning
--- ---
You can use the version script to create a new documentation version based on the latest content in the `docs` directory. That specific set of documentation will then be preserved and accessible even as the documentation in the `docs` directory changes moving forward. You can use the version script to create a new documentation version based on the latest content in the `docs` directory. That specific set of documentation will then be preserved and accessible even as the documentation in the `docs` directory changes moving forward.
@ -61,7 +62,7 @@ npm run docusaurus docs:version 1.1.0
When tagging a new version, the document versioning mechanism will: When tagging a new version, the document versioning mechanism will:
- Copy the full `docs/` folder contents into a new `versioned_docs/version-<version>/` folder. - Copy the full `docs/` folder contents into a new `versioned_docs/version-<version>/` folder.
- Create a versioned sidebars file based from your current [sidebar](docs.md#sidebar) configuration (if it exists) - saved as `versioned_sidebars/version-<version>-sidebars.json`. - Create a versioned sidebars file based from your current [sidebar](docs-introduction.md#sidebar) configuration (if it exists) - saved as `versioned_sidebars/version-<version>-sidebars.json`.
- Append the new version number to `versions.json`. - Append the new version number to `versions.json`.
## Docs ## Docs
@ -165,7 +166,7 @@ Docusaurus defaults work great for the first usecase.
The docs in `./docs` will be served at `/docs/1.0.0` instead of `/docs/next`, and `1.0.0` will become the default version we link to in the navbar dropdown, and you will only need to maintain a single `./docs` folder. The docs in `./docs` will be served at `/docs/1.0.0` instead of `/docs/next`, and `1.0.0` will become the default version we link to in the navbar dropdown, and you will only need to maintain a single `./docs` folder.
See [docs plugin configuration](./api/plugins/plugin-content-docs.md) for more details. See [docs plugin configuration](../../api/plugins/plugin-content-docs.md) for more details.
### Version your documentation only when needed ### Version your documentation only when needed

View file

@ -0,0 +1,86 @@
---
id: admonitions
title: Admonitions
description: Handling admonitions/callouts in Docusaurus Markdown
slug: /markdown-features/admonitions
---
In addition to the basic Markdown syntax, we use [remark-admonitions](https://github.com/elviswolcott/remark-admonitions) alongside MDX to add support for admonitions. Admonitions are wrapped by a set of 3 colons.
Example:
:::note
The content and title *can* include markdown.
:::
:::tip You can specify an optional title
Heads up! Here's a pro-tip.
:::
:::info
Useful information.
:::
:::caution
Warning! You better pay attention!
:::
:::danger
Danger danger, mayday!
:::
:::note
The content and title _can_ include markdown.
:::
:::tip You can specify an optional title
Heads up! Here's a pro-tip.
:::
:::info
Useful information.
:::
:::caution
Warning! You better pay attention!
:::
:::danger
Danger danger, mayday!
:::
## Specifying title
You may also specify an optional title
:::note Your Title
The content and title *can* include markdown.
:::
:::note Your Title
The content and title _can_ include Markdown.
:::

View file

@ -0,0 +1,145 @@
---
id: assets
title: Assets
description: Handling assets in Docusaurus Markdown
slug: /markdown-features/assets
---
Sometimes you want to link to static assets directly from Markdown files, and it is convenient to co-locate the asset next to the markdown file using it.
We have setup Webpack loaders to handle most common file types, so that when you import a file, you get its url, and the asset is automatically copied to the output folder.
Let's imagine the following file structure:
```
# Your doc
/website/docs/myFeature.mdx
# Some assets you want to use
/website/docs/assets/docusaurus-asset-example-banner.png
/website/docs/assets/docusaurus-asset-example-pdf.pdf
```
## Images
You can use images in Markdown, or by requiring them and using a JSX image tag:
```mdx
# My Markdown page
<img
src={require('./assets/docusaurus-asset-example-banner.png').default}
alt="Example banner"
/>
or
![Example banner](./assets/docusaurus-asset-example-banner.png)
```
The ES imports syntax also works:
```mdx
# My Markdown page
import myImageUrl from './assets/docusaurus-asset-example-banner.png';
<img src={myImageUrl)} alt="My image alternative text" />
```
This results in displaying the image:
![My image alternative text](../../assets/docusaurus-asset-example-banner.png)
:::note
If you are using [@docusaurus/plugin-ideal-image](../../using-plugins.md#docusaurusplugin-ideal-image), you need to use the dedicated image component, as documented.
:::
## Files
In the same way, you can link to existing assets by requiring them and using the returned url in videos, links etc.
```mdx
# My Markdown page
<a
target="_blank"
href={require('./assets/docusaurus-asset-example-pdf.pdf').default}>
Download this PDF
</a>
or
[Download this PDF using Markdown](./assets/docusaurus-asset-example-pdf.pdf)
```
<a
target="_blank"
href={require('../../assets/docusaurus-asset-example-pdf.pdf').default}>
Download this PDF
</a>
[Download this PDF using Markdown](../../assets/docusaurus-asset-example-pdf.pdf)
## Inline SVGs
Docusaurus supports inlining SVGs out of the box.
```jsx
import DocusaurusSvg from './docusaurus.svg';
<DocusaurusSvg />;
```
import DocusaurusSvg from '@site/static/img/docusaurus.svg';
<DocusaurusSvg />
This can be useful, if you want to alter the part of the SVG image via CSS. For example, you can change one of the SVG colors based on the current theme.
```jsx
import DocusaurusSvg from './docusaurus.svg';
<DocusaurusSvg className="themedDocusaurus" />;
```
```css
html[data-theme='light'] .themedDocusaurus [fill='#FFFF50'] {
fill: greenyellow;
}
html[data-theme='dark'] .themedDocusaurus [fill='#FFFF50'] {
fill: seagreen;
}
```
<DocusaurusSvg className="themedDocusaurus" />
## Themed Images
Docusaurus supports themed images: the `ThemedImage` component (included in the classic/bootstrap themes) allows you to switch the image source based on the current theme.
```jsx {5-8}
import ThemedImage from '@theme/ThemedImage';
<ThemedImage
alt="Docusaurus themed image"
sources={{
light: useBaseUrl('img/docusaurus_light.svg'),
dark: useBaseUrl('img/docusaurus_dark.svg'),
}}
/>;
```
import useBaseUrl from '@docusaurus/useBaseUrl';
import ThemedImage from '@theme/ThemedImage';
<ThemedImage
alt="Docusaurus themed image"
sources={{
light: useBaseUrl('img/docusaurus_keytar.svg'),
dark: useBaseUrl('img/docusaurus_speed.svg'),
}}
/>

View file

@ -0,0 +1,439 @@
---
id: code-blocks
title: Code blocks
description: Handling code blocks in Docusaurus Markdown
slug: /markdown-features/code-blocks
---
Code blocks within documentation are super-powered 💪.
## Code title
You can add a title to the code block by adding `title` key after the language (leave a space between them).
```jsx title="/src/components/HelloCodeTitle.js"
function HelloCodeTitle(props) {
return <h1>Hello, {props.name}</h1>;
}
```
```jsx title="/src/components/HelloCodeTitle.js"
function HelloCodeTitle(props) {
return <h1>Hello, {props.name}</h1>;
}
```
## Syntax highlighting
Code blocks are text blocks wrapped around by strings of 3 backticks. You may check out [this reference](https://github.com/mdx-js/specification) for specifications of MDX.
```jsx
console.log('Every repo must come with a mascot.');
```
<!-- TODO: We need to allow users to pick syntax highlighting themes (maybe other than swizzling) -->
Use the matching language meta string for your code block, and Docusaurus will pick up syntax highlighting automatically, powered by [Prism React Renderer](https://github.com/FormidableLabs/prism-react-renderer).
```jsx
console.log('Every repo must come with a mascot.');
```
By default, the Prism [syntax highlighting theme](https://github.com/FormidableLabs/prism-react-renderer#theming) we use is [Palenight](https://github.com/FormidableLabs/prism-react-renderer/blob/master/src/themes/palenight.js). You can change this to another theme by passing `theme` field in `prism` as `themeConfig` in your docusaurus.config.js.
For example, if you prefer to use the `dracula` highlighting theme:
```js {4} title="docusaurus.config.js"
module.exports = {
themeConfig: {
prism: {
theme: require('prism-react-renderer/themes/dracula'),
},
},
};
```
By default, Docusaurus comes with this subset of [commonly used languages](https://github.com/FormidableLabs/prism-react-renderer/blob/master/src/vendor/prism/includeLangs.js).
To add syntax highlighting for any of the other [Prism supported languages](https://prismjs.com/#supported-languages), define it in an array of additional languages.
For example, if you want to add highlighting for the `powershell` language:
```js {5} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
prism: {
additionalLanguages: ['powershell'],
},
// ...
},
};
```
If you want to add highlighting for languages not yet supported by Prism, you can swizzle `prism-include-languages`:
```bash npm2yarn
npm run swizzle @docusaurus/theme-classic prism-include-languages
```
It will produce `prism-include-languages.js` in your `src/theme` folder. You can add highlighting support for custom languages by editing `prism-include-languages.js`:
```js {8} title="src/theme/prism-include-languages.js"
const prismIncludeLanguages = (Prism) => {
// ...
additionalLanguages.forEach((lang) => {
require(`prismjs/components/prism-${lang}`); // eslint-disable-line
});
require('/path/to/your/prism-language-definition');
// ...
};
```
You can refer to [Prism's official language definitions](https://github.com/PrismJS/prism/tree/master/components) when you are writing your own language definitions.
## Line highlighting
You can bring emphasis to certain lines of code by specifying line ranges after the language meta string (leave a space after the language).
```jsx {3}
function HighlightSomeText(highlight) {
if (highlight) {
return 'This text is highlighted!';
}
return 'Nothing highlighted';
}
```
```jsx {3}
function HighlightSomeText(highlight) {
if (highlight) {
return 'This text is highlighted!';
}
return 'Nothing highlighted';
}
```
To accomplish this, Docusaurus adds the `docusaurus-highlight-code-line` class to the highlighted lines. You will need to define your own styling for this CSS, possibly in your `src/css/custom.css` with a custom background color which is dependent on your selected syntax highlighting theme. The color given below works for the default highlighting theme (Palenight), so if you are using another theme, you will have to tweak the color accordingly.
```css title="/src/css/custom.css"
.docusaurus-highlight-code-line {
background-color: rgb(72, 77, 91);
display: block;
margin: 0 calc(-1 * var(--ifm-pre-padding));
padding: 0 var(--ifm-pre-padding);
}
/* If you have a different syntax highlighting theme for dark mode. */
html[data-theme='dark'] .docusaurus-highlight-code-line {
background-color: ; /* Color which works with dark mode syntax highlighting theme */
}
```
To highlight multiple lines, separate the line numbers by commas or use the range syntax to select a chunk of lines. This feature uses the `parse-number-range` library and you can find [more syntax](https://www.npmjs.com/package/parse-numeric-range) on their project details.
```jsx {1,4-6,11}
import React from 'react';
function MyComponent(props) {
if (props.isBar) {
return <div>Bar</div>;
}
return <div>Foo</div>;
}
export default MyComponent;
```
```jsx {1,4-6,11}
import React from 'react';
function MyComponent(props) {
if (props.isBar) {
return <div>Bar</div>;
}
return <div>Foo</div>;
}
export default MyComponent;
```
You can also use comments with `highlight-next-line`, `highlight-start`, and `highlight-end` to select which lines are highlighted.
```jsx
function HighlightSomeText(highlight) {
if (highlight) {
// highlight-next-line
return 'This text is highlighted!';
}
return 'Nothing highlighted';
}
function HighlightMoreText(highlight) {
// highlight-start
if (highlight) {
return 'This range is highlighted!';
}
// highlight-end
return 'Nothing highlighted';
}
```
```jsx
function HighlightSomeText(highlight) {
if (highlight) {
// highlight-next-line
return 'This text is highlighted!';
}
return 'Nothing highlighted';
}
function HighlightMoreText(highlight) {
// highlight-start
if (highlight) {
return 'This range is highlighted!';
}
// highlight-end
return 'Nothing highlighted';
}
```
Supported commenting syntax:
| Language | Syntax |
| ---------- | ------------------------ |
| JavaScript | `/* ... */` and `// ...` |
| JSX | `{/* ... */}` |
| Python | `# ...` |
| HTML | `<!-- ... -->` |
If there's a syntax that is not currently supported, we are open to adding them! Pull requests welcome.
## Interactive code editor
(Powered by [React Live](https://github.com/FormidableLabs/react-live))
You can create an interactive coding editor with the `@docusaurus/theme-live-codeblock` plugin.
First, add the plugin to your package.
```bash npm2yarn
npm install --save @docusaurus/theme-live-codeblock
```
You will also need to add the plugin to your `docusaurus.config.js`.
```js {3}
module.exports = {
// ...
themes: ['@docusaurus/theme-live-codeblock'],
// ...
};
```
To use the plugin, create a code block with `live` attached to the language meta string.
```jsx live
function Clock(props) {
const [date, setDate] = useState(new Date());
useEffect(() => {
var timerID = setInterval(() => tick(), 1000);
return function cleanup() {
clearInterval(timerID);
};
});
function tick() {
setDate(new Date());
}
return (
<div>
<h2>It is {date.toLocaleTimeString()}.</h2>
</div>
);
}
```
The code block will be rendered as an interactive editor. Changes to the code will reflect on the result panel live.
```jsx live
function Clock(props) {
const [date, setDate] = useState(new Date());
useEffect(() => {
var timerID = setInterval(() => tick(), 1000);
return function cleanup() {
clearInterval(timerID);
};
});
function tick() {
setDate(new Date());
}
return (
<div>
<h2>It is {date.toLocaleTimeString()}.</h2>
</div>
);
}
```
:::caution react-live and imports
It is not possible to import components directly from the react-live code editor, you have to define available imports upfront.
:::
By default, all React imports are available. If you need more imports available, swizzle the react-live scope:
```bash npm2yarn
npm run swizzle @docusaurus/theme-live-codeblock ReactLiveScope
```
```jsx {3-15,21} title="src/theme/ReactLiveScope/index.js"
import React from 'react';
const ButtonExample = (props) => (
<button
{...props}
style={{
backgroundColor: 'white',
border: 'solid red',
borderRadius: 20,
padding: 10,
cursor: 'pointer',
...props.style,
}}
/>
);
// Add react-live imports you need here
const ReactLiveScope = {
React,
...React,
ButtonExample,
};
export default ReactLiveScope;
```
The `ButtonExample` component is now available to use:
```jsx live
function MyPlayground(props) {
return (
<div>
<ButtonExample onClick={() => alert('hey!')}>Click me</ButtonExample>
</div>
);
}
```
## Multi-language support code blocks
With MDX, you can easily create interactive components within your documentation, for example, to display code in multiple programming languages and switching between them using a tabs component.
Instead of implementing a dedicated component for multi-language support code blocks, we've implemented a generic Tabs component in the classic theme so that you can use it for other non-code scenarios as well.
The following example is how you can have multi-language code tabs in your docs. Note that the empty lines above and below each language block is **intentional**. This is a current limitation of MDX, you have to leave empty lines around Markdown syntax for the MDX parser to know that it's Markdown syntax and not JSX.
````jsx
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
<Tabs
defaultValue="js"
values={[
{ label: 'JavaScript', value: 'js', },
{ label: 'Python', value: 'py', },
{ label: 'Java', value: 'java', },
]
}>
<TabItem value="js">
```js
function helloWorld() {
console.log('Hello, world!');
}
```
</TabItem>
<TabItem value="py">
```py
def hello_world():
print 'Hello, world!'
```
</TabItem>
<TabItem value="java">
```java
class HelloWorld {
public static void main(String args[]) {
System.out.println("Hello, World");
}
}
```
</TabItem>
</Tabs>
````
And you will get the following:
<Tabs
defaultValue="js"
values={[
{ label: 'JavaScript', value: 'js', },
{ label: 'Python', value: 'py', },
{ label: 'Java', value: 'java', },
]
}>
<TabItem value="js">
```js
function helloWorld() {
console.log('Hello, world!');
}
```
</TabItem>
<TabItem value="py">
```py
def hello_world():
print 'Hello, world!'
```
</TabItem>
<TabItem value="java">
```java
class HelloWorld {
public static void main(String args[]) {
System.out.println("Hello, World");
}
}
```
</TabItem>
</Tabs>
You may want to implement your own `<MultiLanguageCode />` abstraction if you find the above approach too verbose. We might just implement one in future for convenience.
If you have multiple of these multi-language code tabs, and you want to sync the selection across the tab instances, refer to the [Syncing tab choices section](#syncing-tab-choices).

View file

@ -0,0 +1,117 @@
---
id: inline-toc
title: Inline TOC
description: Using inline table-of-contents inside Docusaurus Markdown
slug: /markdown-features/inline-toc
---
import BrowserWindow from '@site/src/components/BrowserWindow';
Each markdown document displays a tab of content on the top-right corner.
But it is also possible to display an inline table of contents directly inside a markdown document, thanks to MDX.
## Full table of contents
The `toc` variable is available in any MDX document, and contain all the top level headings of a MDX document.
```jsx
import TOCInline from '@theme/TOCInline';
<TOCInline toc={toc} />;
```
import TOCInline from '@theme/TOCInline';
<BrowserWindow>
<TOCInline toc={toc} />
</BrowserWindow>
## Custom table of contents
The `toc` props is just a list of table of contents items:
```ts
type TOCItem = {
value: string;
id: string;
children: TOCItem[];
};
```
You can create this TOC tree manually, or derive a new TOC tree from the `toc` variable:
```jsx
import TOCInline from '@theme/TOCInline';
<TOCInline
toc={
// Only show 3th and 5th top-level heading
[toc[2], toc[4]]
}
/>;
```
<BrowserWindow>
<TOCInline toc={[toc[2], toc[4]]} />
</BrowserWindow>
---
:::caution
The underlying content is just an example to have more table-of-contents items available in current page.
:::
## Example Section 1
Lorem ipsum
### Example Subsection 1 a
Lorem ipsum
### Example Subsection 1 b
Lorem ipsum
### Example Subsection 1 c
Lorem ipsum
## Example Section 2
Lorem ipsum
### Example Subsection 2 a
Lorem ipsum
### Example Subsection 2 b
Lorem ipsum
### Example Subsection 2 c
Lorem ipsum
## Example Section 3
Lorem ipsum
### Example Subsection 3 a
Lorem ipsum
### Example Subsection 3 b
Lorem ipsum
### Example Subsection 3 c
Lorem ipsum

View file

@ -0,0 +1,23 @@
---
id: introduction
title: Markdown Features introduction
sidebar_label: Introduction
description: Docusaurus uses GitHub Flavored Markdown (GFM). Find out more about Docusaurus-specific features when writing Markdown.
slug: /markdown-features
---
Documentation is one of your product's interfaces with your users. A well-written and well-organized set of docs helps your users understand your product quickly. Our aligned goal here is to help your users find and understand the information they need, as quickly as possible.
Docusaurus 2 uses modern tooling to help you compose your interactive documentations with ease. You may embed React components, or build live coding blocks where your users may play with the code on the spot. Start sharing your eureka moments with the code your audience cannot walk away from. It is perhaps the most effective way of attracting potential users.
In this section, we'd like to introduce you to the tools we've picked that we believe will help you build a powerful documentation. Let us walk you through with an example.
Markdown is a syntax that enables you to write formatted content in a readable syntax.
The [standard Markdown syntax](https://daringfireball.net/projects/markdown/syntax) is supported, and we use [MDX](https://mdxjs.com/) as the parsing engine, which can do much more than just parsing Markdown, like rendering React components inside your documents.
:::important
This section assumes you are using the official Docusaurus content plugins.
:::

View file

@ -0,0 +1,78 @@
---
id: plugins
title: Plugins
description: Using MDX plugins to expand Docusaurus Markdown functionalities
slug: /markdown-features/plugins
---
You can expand the MDX functionalities, using plugins.
Docusaurus content plugins support both [Remark](https://github.com/remarkjs/remark) and [Rehype](https://github.com/rehypejs/rehype) plugins that work with MDX.
## Configuring plugins
An MDX plugin is usually a npm package, so you install them like other npm packages using npm.
First, install your [Remark](https://github.com/remarkjs/remark/blob/main/doc/plugins.md#list-of-plugins) and [Rehype](https://github.com/rehypejs/rehype/blob/main/doc/plugins.md#list-of-plugins) plugins.
For example:
```bash npm2yarn
npm install --save remark-images
npm install --save rehype-truncate
```
Next, import the plugins:
```js
const remarkImages = require('remark-images');
const rehypeTruncate = require('rehype-truncate');
```
Finally, add them to the `@docusaurus/preset-classic` options in `docusaurus.config.js`:
```js {10,11} title="docusaurus.config.js"
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
docs: {
sidebarPath: require.resolve('./sidebars.js'),
// ...
remarkPlugins: [remarkImages],
rehypePlugins: [rehypeTruncate],
},
},
],
],
};
```
## Configuring plugin options
Some plugins can be configured and accept their own options. In that case, use the `[plugin, pluginOptions]` syntax, like so:
```jsx {10-13} title="docusaurus.config.js"
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
docs: {
sidebarPath: require.resolve('./sidebars.js'),
// ...
remarkPlugins: [
plugin1,
[plugin2, {option1: {...}}],
],
},
},
],
],
};
```
See more information in the [MDX documentation](https://mdxjs.com/advanced/plugins).

View file

@ -0,0 +1,69 @@
---
id: react
title: Using React
description: Using the power of React in Docusaurus Markdown documents, thanks to MDX
slug: /markdown-features/react
---
import BrowserWindow from '@site/src/components/BrowserWindow';
Docusaurus has built-in support for [MDX](https://mdxjs.com/), which allows you to write JSX within your Markdown files and render them as React components.
:::note
While both `.md` and `.mdx` files are parsed using MDX, some of the syntax are treated slightly differently. For the most accurate parsing and better editor support, we recommend using the `.mdx` extension for files containing MDX syntax.
:::
Try this block here:
```jsx
export const Highlight = ({children, color}) => (
<span
style={{
backgroundColor: color,
borderRadius: '2px',
color: '#fff',
padding: '0.2rem',
}}>
{children}
</span>
);
<Highlight color="#25c2a0">Docusaurus green</Highlight> and <Highlight color="#1877F2">Facebook blue</Highlight> are my favorite colors.
I can write **Markdown** alongside my _JSX_!
```
Notice how it renders both the markup from your React component and the Markdown syntax:
export const Highlight = ({children, color}) => (
<span
style={{
backgroundColor: color,
borderRadius: '2px',
color: '#fff',
padding: '0.2rem',
}}>
{children}
</span>
);
<BrowserWindow minHeight={240} url="http://localhost:3000">
<Highlight color="#25c2a0">Docusaurus green</Highlight>
{` `}and <Highlight color="#1877F2">Facebook blue</Highlight> are my favorite colors.
I can write **Markdown** alongside my _JSX_!
</BrowserWindow>
<br />
You can also import your own components defined in other files or third-party components installed via npm! Check out the [MDX docs](https://mdxjs.com/) to see what other fancy stuff you can do with MDX.
:::caution
Since all doc files are parsed using MDX, any HTML is treated as JSX. Therefore, if you need to inline-style a component, follow JSX flavor and provide style objects. This behavior is different from Docusaurus 1. See also [Migrating from v1 to v2](../../migration/migration-manual.md#convert-style-attributes-to-style-objects-in-mdx).
:::

View file

@ -0,0 +1,218 @@
---
id: tabs
title: Tabs
description: Using tabs inside Docusaurus Markdown
slug: /markdown-features/tabs
---
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
To show tabbed content within Markdown files, you can fall back on MDX. Docusaurus provides `<Tabs>` components out-of-the-box.
```jsx
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
<Tabs
defaultValue="apple"
values={[
{label: 'Apple', value: 'apple'},
{label: 'Orange', value: 'orange'},
{label: 'Banana', value: 'banana'},
]}>
<TabItem value="apple">This is an apple 🍎</TabItem>
<TabItem value="orange">This is an orange 🍊</TabItem>
<TabItem value="banana">This is a banana 🍌</TabItem>
</Tabs>;
```
And you will get the following:
<Tabs
defaultValue="apple"
values={[
{label: 'Apple', value: 'apple'},
{label: 'Orange', value: 'orange'},
{label: 'Banana', value: 'banana'},
]}>
<TabItem value="apple">This is an apple 🍎</TabItem>
<TabItem value="orange">This is an orange 🍊</TabItem>
<TabItem value="banana">This is a banana 🍌</TabItem>
</Tabs>
:::info
By default, tabs are rendered eagerly, but it is possible to load them lazily by passing the `lazy` prop to the `Tabs` component.
:::
## Syncing tab choices
You may want choices of the same kind of tabs to sync with each other. For example, you might want to provide different instructions for users on Windows vs users on macOS, and you want to changing all OS-specific instructions tabs in one click. To achieve that, you can give all related tabs the same `groupId` prop. Note that doing this will persist the choice in `localStorage` and all `<Tab>` instances with the same `groupId` will update automatically when the value of one of them is changed. Note that `groupID` are globally-namespaced.
```jsx {2,14}
<Tabs
groupId="operating-systems"
defaultValue="win"
values={[
{label: 'Windows', value: 'win'},
{label: 'macOS', value: 'mac'},
]
}>
<TabItem value="win">Use Ctrl + C to copy.</TabItem>
<TabItem value="mac">Use Command + C to copy.</TabItem>
</Tabs>
<Tabs
groupId="operating-systems"
defaultValue="win"
values={[
{label: 'Windows', value: 'win'},
{label: 'macOS', value: 'mac'},
]
}>
<TabItem value="win">Use Ctrl + V to paste.</TabItem>
<TabItem value="mac">Use Command + V to paste.</TabItem>
</Tabs>
```
<Tabs
groupId="operating-systems"
defaultValue="win"
values={[
{label: 'Windows', value: 'win'},
{label: 'macOS', value: 'mac'},
]}>
<TabItem value="win">Use Ctrl + C to copy.</TabItem>
<TabItem value="mac">Use Command + C to copy.</TabItem>
</Tabs>
<Tabs
groupId="operating-systems"
defaultValue="win"
values={[
{label: 'Windows', value: 'win'},
{label: 'macOS', value: 'mac'},
]}>
<TabItem value="win">Use Ctrl + V to paste.</TabItem>
<TabItem value="mac">Use Command + V to paste.</TabItem>
</Tabs>
For all tab groups that have the same `groupId`, the possible values do not need to be the same. If one tab group with chooses an value that does not exist in another tab group with the same `groupId`, the tab group with the missing value won't change its tab. You can see that from the following example. Try to select Linux, and the above tab groups doesn't change.
```jsx
<Tabs
groupId="operating-systems"
defaultValue="win"
values={[
{label: 'Windows', value: 'win'},
{label: 'macOS', value: 'mac'},
{label: 'Linux', value: 'linux'},
]}>
<TabItem value="win">I am Windows.</TabItem>
<TabItem value="mac">I am macOS.</TabItem>
<TabItem value="linux">I am Linux.</TabItem>
</Tabs>
```
<Tabs
groupId="operating-systems"
defaultValue="win"
values={[
{label: 'Windows', value: 'win'},
{label: 'macOS', value: 'mac'},
{label: 'Linux', value: 'linux'},
]}>
<TabItem value="win">I am Windows.</TabItem>
<TabItem value="mac">I am macOS.</TabItem>
<TabItem value="linux">I am Linux.</TabItem>
</Tabs>
---
Tab choices with different `groupId`s will not interfere with each other:
```jsx {2,14}
<Tabs
groupId="operating-systems"
defaultValue="win"
values={[
{label: 'Windows', value: 'win'},
{label: 'macOS', value: 'mac'},
]
}>
<TabItem value="win">Windows in windows.</TabItem>
<TabItem value="mac">macOS is macOS.</TabItem>
</Tabs>
<Tabs
groupId="non-mac-operating-systems"
defaultValue="win"
values={[
{label: 'Windows', value: 'win'},
{label: 'Unix', value: 'unix'},
]
}>
<TabItem value="win">Windows is windows.</TabItem>
<TabItem value="unix">Unix is unix.</TabItem>
</Tabs>
```
<Tabs
groupId="operating-systems"
defaultValue="win"
values={[
{label: 'Windows', value: 'win'},
{label: 'macOS', value: 'mac'},
]}>
<TabItem value="win">Windows in windows.</TabItem>
<TabItem value="mac">macOS is macOS.</TabItem>
</Tabs>
<Tabs
groupId="non-mac-operating-systems"
defaultValue="win"
values={[
{label: 'Windows', value: 'win'},
{label: 'Unix', value: 'unix'},
]}>
<TabItem value="win">Windows is windows.</TabItem>
<TabItem value="unix">Unix is unix.</TabItem>
</Tabs>
## Customizing tabs
You might want to customize the appearance of certain set of tabs. To do that you can pass the string in `className` prop and the specified CSS class will be added to the `Tabs` component:
```jsx {5}
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
<Tabs
className="unique-tabs"
defaultValue="apple"
values={[
{label: 'Apple', value: 'apple'},
{label: 'Orange', value: 'orange'},
{label: 'Banana', value: 'banana'},
]}>
<TabItem value="apple">This is an apple 🍎</TabItem>
<TabItem value="orange">This is an orange 🍊</TabItem>
<TabItem value="banana">This is a banana 🍌</TabItem>
</Tabs>;
```
<Tabs
className="unique-tabs"
defaultValue="apple"
values={[
{label: 'Apple', value: 'apple'},
{label: 'Orange', value: 'orange'},
{label: 'Banana', value: 'banana'},
]}>
<TabItem value="apple">This is an apple 🍎</TabItem>
<TabItem value="orange">This is an orange 🍊</TabItem>
<TabItem value="banana">This is a banana 🍌</TabItem>
</Tabs>

View file

@ -71,7 +71,7 @@ my-website
### Project structure rundown ### Project structure rundown
- `/blog/` - Contains the blog Markdown files. You can delete the directory if you do not want/need a blog. More details can be found in the [blog guide](blog.md). - `/blog/` - Contains the blog Markdown files. You can delete the directory if you do not want/need a blog. More details can be found in the [blog guide](blog.md).
- `/docs/` - Contains the Markdown files for the docs. Customize the order of the docs sidebar in `sidebars.js`. More details can be found in the [docs guide](markdown-features.mdx). - `/docs/` - Contains the Markdown files for the docs. Customize the order of the docs sidebar in `sidebars.js`. More details can be found in the [docs guide](./guides/docs/docs-markdown-features.mdx).
- `/src/` - Non-documentation files like pages or custom React components. You don't have to strictly put your non-documentation files in here but putting them under a centralized directory makes it easier to specify in case you need to do some sort of linting/processing - `/src/` - Non-documentation files like pages or custom React components. You don't have to strictly put your non-documentation files in here but putting them under a centralized directory makes it easier to specify in case you need to do some sort of linting/processing
- `/src/pages` - Any files within this directory will be converted into a website page. More details can be found in the [pages guide](guides/creating-pages.md). - `/src/pages` - Any files within this directory will be converted into a website page. More details can be found in the [pages guide](guides/creating-pages.md).
- `/static/` - Static directory. Any contents inside here will be copied into the root of the final `build` directory. - `/static/` - Static directory. Any contents inside here will be copied into the root of the final `build` directory.

File diff suppressed because it is too large Load diff

View file

@ -455,7 +455,7 @@ If you want to keep the `.html` extension as the canonical url of a page, docs c
### Sidebar ### Sidebar
In previous version, nested sidebar category is not allowed and sidebar category can only contain doc id. However, v2 allows infinite nested sidebar and we have many types of [Sidebar Item](docs.md#sidebar-item) other than document. In previous version, nested sidebar category is not allowed and sidebar category can only contain doc id. However, v2 allows infinite nested sidebar and we have many types of [Sidebar Item](../guides/docs/sidebar.md#understanding-sidebar-items) other than document.
You'll have to migrate your sidebar if it contains category type. Rename `subcategory` to `category` and `ids` to `items`. You'll have to migrate your sidebar if it contains category type. Rename `subcategory` to `category` and `ids` to `items`.
@ -556,7 +556,7 @@ The following code could be helpful for migration of various pages:
### Replace AUTOGENERATED_TABLE_OF_CONTENTS ### Replace AUTOGENERATED_TABLE_OF_CONTENTS
This feature is replaced by [inline table of content](../markdown-features.mdx#inline-table-of-contents) This feature is replaced by [inline table of content](../guides/markdown-features/markdown-features-inline-toc.mdx)
### Update Markdown syntax to be MDX-compatible ### Update Markdown syntax to be MDX-compatible
@ -568,7 +568,7 @@ Frontmatter is parsed by [gray-matter](https://github.com/jonschlinkert/gray-mat
### Language-specific code tabs ### Language-specific code tabs
Refer to the [multi-language support code blocks](markdown-features.mdx#multi-language-support-code-blocks) section. Refer to the [multi-language support code blocks](../guides/markdown-features/markdown-features-code-blocks.mdx#multi-language-support-code-blocks) section.
### Front matter ### Front matter

View file

@ -23,17 +23,32 @@ module.exports = {
label: 'Guides', label: 'Guides',
items: [ items: [
'guides/creating-pages', 'guides/creating-pages',
'styling-layout',
'static-assets',
{ {
Docs: [ Docs: [
'docs-introduction', 'guides/docs/introduction',
'docs-sidebar', 'guides/docs/create-doc',
'markdown-features', 'guides/docs/markdown-features',
'versioning', 'guides/docs/sidebar',
'guides/docs/versioning',
], ],
}, },
'blog', 'blog',
{
type: 'category',
label: 'Markdown Features',
items: [
'guides/markdown-features/introduction',
'guides/markdown-features/react',
'guides/markdown-features/tabs',
'guides/markdown-features/code-blocks',
'guides/markdown-features/admonitions',
'guides/markdown-features/inline-toc',
'guides/markdown-features/assets',
'guides/markdown-features/plugins',
],
},
'styling-layout',
'static-assets',
'search', 'search',
'deployment', 'deployment',
], ],