feat: details/summary theme / MDX component (#5216)

* Details component

* polish arrow animation

* fix text selection bug

* fix some edge cases + polish

* example of overriding baseClassName

* Move Details component to theme-common

* make component work even when JS is disabled or failed to load

* update arrow transform

* Details component: better handling of no-JS fallback mode: avoid delaying arrow navigation when JS (see review)

* prefix css vars with --docusaurus

* improve css arrow styling

* slightly change details/summary design

* better md doc + include quotes and details in doc
This commit is contained in:
Sébastien Lorber 2021-07-27 18:45:12 +02:00 committed by GitHub
parent 798f634007
commit dc4664b489
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
13 changed files with 378 additions and 21 deletions

View file

@ -0,0 +1,24 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import clsx from 'clsx';
import {Details as DetailsGeneric} from '@docusaurus/theme-common';
import type {Props} from '@theme/Details';
import styles from './styles.module.css';
// Should we have a custom details/summary comp in Infima instead of reusing alert classes?
const InfimaClasses = 'alert alert--info';
export default function Details({...props}: Props): JSX.Element {
return (
<DetailsGeneric
{...props}
className={clsx(InfimaClasses, styles.details, props.className)}
/>
);
}

View file

@ -0,0 +1,13 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
.details {
--docusaurus-details-decoration-color: var(--ifm-alert-border-color);
--docusaurus-details-transition: transform var(--ifm-transition-fast) ease;
margin: 0 0 var(--ifm-spacing-vertical);
border: 1px solid var(--ifm-alert-border-color);
}

View file

@ -5,10 +5,11 @@
* LICENSE file in the root directory of this source tree. * LICENSE file in the root directory of this source tree.
*/ */
import React, {isValidElement} from 'react'; import React, {ComponentProps, isValidElement, ReactElement} from 'react';
import Link from '@docusaurus/Link'; import Link from '@docusaurus/Link';
import CodeBlock, {Props} from '@theme/CodeBlock'; import CodeBlock, {Props} from '@theme/CodeBlock';
import Heading from '@theme/Heading'; import Heading from '@theme/Heading';
import Details from '@theme/Details';
import type {MDXComponentsObject} from '@theme/MDXComponents'; import type {MDXComponentsObject} from '@theme/MDXComponents';
const MDXComponents: MDXComponentsObject = { const MDXComponents: MDXComponentsObject = {
@ -44,6 +45,20 @@ const MDXComponents: MDXComponentsObject = {
/> />
); );
}, },
details: (props): JSX.Element => {
const items = React.Children.toArray(props.children);
// Split summary item from the rest to pass it as a separate prop to the Detais theme component
const summary: ReactElement<
ComponentProps<'summary'>
> = (items as any[]).find((item) => item?.props?.mdxType === 'summary');
const children = <>{items.filter((item) => item !== summary)}</>;
return (
<Details {...props} summary={summary}>
{children}
</Details>
);
},
h1: Heading('h1'), h1: Heading('h1'),
h2: Heading('h2'), h2: Heading('h2'),
h3: Heading('h3'), h3: Heading('h3'),

View file

@ -328,6 +328,7 @@ declare module '@theme/MDXComponents' {
readonly code: typeof CodeBlock; readonly code: typeof CodeBlock;
readonly a: (props: ComponentProps<'a'>) => JSX.Element; readonly a: (props: ComponentProps<'a'>) => JSX.Element;
readonly pre: typeof CodeBlock; readonly pre: typeof CodeBlock;
readonly details: (props: ComponentProps<'details'>) => JSX.Element;
readonly h1: (props: ComponentProps<'h1'>) => JSX.Element; readonly h1: (props: ComponentProps<'h1'>) => JSX.Element;
readonly h2: (props: ComponentProps<'h2'>) => JSX.Element; readonly h2: (props: ComponentProps<'h2'>) => JSX.Element;
readonly h3: (props: ComponentProps<'h3'>) => JSX.Element; readonly h3: (props: ComponentProps<'h3'>) => JSX.Element;
@ -529,6 +530,12 @@ declare module '@theme/ThemedImage' {
export default ThemedImage; export default ThemedImage;
} }
declare module '@theme/Details' {
export type Props = import('@docusaurus/theme-common').Details;
const Props: (props: Props) => JSX.Element;
export default Props;
}
declare module '@theme/ThemeProvider' { declare module '@theme/ThemeProvider' {
import type {ReactNode} from 'react'; import type {ReactNode} from 'react';

View file

@ -0,0 +1,20 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const path = require('path');
const fs = require('fs-extra');
/**
* Copy all untyped and static assets files to lib.
*/
const srcDir = path.resolve(__dirname, 'src');
const libDir = path.resolve(__dirname, 'lib');
fs.copySync(srcDir, libDir, {
filter(filepath) {
return !/__tests__/.test(filepath) && !/\.tsx?$/.test(filepath);
},
});

View file

@ -5,8 +5,8 @@
"main": "./lib/index.js", "main": "./lib/index.js",
"types": "./lib/index.d.ts", "types": "./lib/index.d.ts",
"scripts": { "scripts": {
"build": "tsc", "build": "node copyUntypedFiles.js && tsc",
"watch": "tsc --watch" "watch": "node copyUntypedFiles.js && tsc --watch"
}, },
"publishConfig": { "publishConfig": {
"access": "public" "access": "public"
@ -23,6 +23,8 @@
"@docusaurus/plugin-content-docs": "2.0.0-beta.3", "@docusaurus/plugin-content-docs": "2.0.0-beta.3",
"@docusaurus/plugin-content-pages": "2.0.0-beta.3", "@docusaurus/plugin-content-pages": "2.0.0-beta.3",
"@docusaurus/types": "2.0.0-beta.3", "@docusaurus/types": "2.0.0-beta.3",
"clsx": "^1.1.1",
"fs-extra": "^10.0.0",
"tslib": "^2.1.0" "tslib": "^2.1.0"
}, },
"devDependencies": { "devDependencies": {

View file

@ -164,7 +164,12 @@ type CollapsibleBaseProps = {
collapsed: boolean; collapsed: boolean;
children: ReactNode; children: ReactNode;
animation?: CollapsibleAnimationConfig; animation?: CollapsibleAnimationConfig;
onCollapseTransitionEnd?: (collapsed: boolean) => void;
className?: string; className?: string;
// This is mostly useful for details/summary component where ssrStyle is not needed (as details are hidden natively)
// and can mess-up with the default native behavior of the browser when JS fails to load or is disabled
disableSSRStyle?: boolean;
}; };
function CollapsibleBase({ function CollapsibleBase({
@ -172,7 +177,9 @@ function CollapsibleBase({
collapsed, collapsed,
children, children,
animation, animation,
onCollapseTransitionEnd,
className, className,
disableSSRStyle,
}: CollapsibleBaseProps) { }: CollapsibleBaseProps) {
// any because TS is a pain for HTML element refs, see https://twitter.com/sebastienlorber/status/1412784677795110914 // any because TS is a pain for HTML element refs, see https://twitter.com/sebastienlorber/status/1412784677795110914
const collapsibleRef = useRef<any>(null); const collapsibleRef = useRef<any>(null);
@ -183,7 +190,7 @@ function CollapsibleBase({
<As <As
// @ts-expect-error: see https://twitter.com/sebastienlorber/status/1412784677795110914 // @ts-expect-error: see https://twitter.com/sebastienlorber/status/1412784677795110914
ref={collapsibleRef} ref={collapsibleRef}
style={getSSRStyle(collapsed)} style={disableSSRStyle ? undefined : getSSRStyle(collapsed)}
onTransitionEnd={(e) => { onTransitionEnd={(e) => {
if (e.propertyName !== 'height') { if (e.propertyName !== 'height') {
return; return;
@ -197,10 +204,12 @@ function CollapsibleBase({
parseInt(currentCollapsibleElementHeight, 10) === el.scrollHeight parseInt(currentCollapsibleElementHeight, 10) === el.scrollHeight
) { ) {
applyCollapsedStyle(el, false); applyCollapsedStyle(el, false);
onCollapseTransitionEnd?.(false);
} }
if (currentCollapsibleElementHeight === CollapsedStyles.height) { if (currentCollapsibleElementHeight === CollapsedStyles.height) {
applyCollapsedStyle(el, true); applyCollapsedStyle(el, true);
onCollapseTransitionEnd?.(true);
} }
}} }}
className={className}> className={className}>
@ -239,7 +248,7 @@ type CollapsibleProps = CollapsibleBaseProps & {
lazy: boolean; lazy: boolean;
}; };
export function Collapsible({lazy, ...props}: CollapsibleProps) { export function Collapsible({lazy, ...props}: CollapsibleProps): JSX.Element {
const Comp = lazy ? CollapsibleLazy : CollapsibleBase; const Comp = lazy ? CollapsibleLazy : CollapsibleBase;
return <Comp {...props} />; return <Comp {...props} />;
} }

View file

@ -0,0 +1,94 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, {ComponentProps, ReactElement, useRef, useState} from 'react';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import clsx from 'clsx';
import {useCollapsible, Collapsible} from '../Collapsible';
import styles from './styles.module.css';
function isInSummary(node: HTMLElement | null): boolean {
if (!node) {
return false;
}
return node.tagName === 'SUMMARY' || isInSummary(node.parentElement);
}
function hasParent(node: HTMLElement | null, parent: HTMLElement): boolean {
if (!node) {
return false;
}
return node === parent || hasParent(node.parentElement, parent);
}
export type DetailsProps = {
summary?: ReactElement;
} & ComponentProps<'details'>;
const Details = ({summary, children, ...props}: DetailsProps): JSX.Element => {
const {isClient} = useDocusaurusContext();
const detailsRef = useRef<HTMLDetailsElement>(null);
const {collapsed, setCollapsed} = useCollapsible({
initialState: !props.open,
});
// We use a separate prop because it must be set only after animation completes
// Otherwise close anim won't work
const [open, setOpen] = useState(props.open);
return (
<details
{...props}
ref={detailsRef}
open={open}
data-collapsed={collapsed}
className={clsx(
styles.details,
{[styles.isClient]: isClient},
props.className,
)}
onMouseDown={(e) => {
const target = e.target as HTMLElement;
// Prevent a double-click to highlight summary text
if (isInSummary(target) && e.detail > 1) {
e.preventDefault();
}
}}
onClick={(e) => {
e.stopPropagation(); // For isolation of multiple nested details/summary
const target = e.target as HTMLElement;
const shouldToggle =
isInSummary(target) && hasParent(target, detailsRef.current!);
if (!shouldToggle) {
return;
}
e.preventDefault();
if (collapsed) {
setCollapsed(false);
setOpen(true);
} else {
setCollapsed(true);
// setOpen(false); // Don't do this, it breaks close animation!
}
}}>
{summary}
<Collapsible
lazy={false} // Content might matter for SEO in this case
collapsed={collapsed}
disableSSRStyle // Allows component to work fine even with JS disabled!
onCollapseTransitionEnd={(newCollapsed) => {
setCollapsed(newCollapsed);
setOpen(!newCollapsed);
}}>
<div className={styles.collapsibleContent}>{children}</div>
</Collapsible>
</details>
);
};
export default Details;

View file

@ -0,0 +1,59 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/*
CSS variables, meant to be overriden by final theme
*/
.details {
--docusaurus-details-summary-arrow-size: 0.38rem;
--docusaurus-details-transition: transform 200ms ease;
--docusaurus-details-decoration-color: grey;
}
.details > summary {
position: relative;
cursor: pointer;
list-style: none;
margin-left: 1.8rem;
}
.details > summary::-webkit-details-marker {
display: none;
}
.details > summary:before {
position: absolute;
top: 0.45rem;
left: -1.2rem;
/* CSS-only Arrow */
content: '';
width: 0;
height: 0;
border-top: var(--docusaurus-details-summary-arrow-size) solid transparent;
border-bottom: var(--docusaurus-details-summary-arrow-size) solid transparent;
border-left: var(--docusaurus-details-summary-arrow-size) solid
var(--docusaurus-details-decoration-color);
/* Arrow rotation anim */
transform: rotate(0deg);
transition: var(--docusaurus-details-transition);
transform-origin: calc(var(--docusaurus-details-summary-arrow-size) / 2) 50%;
}
/* When JS disabled/failed to load: we use the open property for arrow animation: */
.details[open]:not(.isClient) > summary:before,
/* When JS works: we use the data-attribute for arrow animation */
.details[data-collapsed='false'].isClient > summary:before {
transform: rotate(90deg);
}
.collapsibleContent {
margin-top: 1rem;
border-top: 1px solid var(--docusaurus-details-decoration-color);
padding-top: 1rem;
}

View file

@ -37,11 +37,14 @@ export {useLocationChange} from './utils/useLocationChange';
export {usePrevious} from './utils/usePrevious'; export {usePrevious} from './utils/usePrevious';
export {useCollapsible, Collapsible} from './utils/useCollapsible'; export {useCollapsible, Collapsible} from './components/Collapsible';
export type { export type {
UseCollapsibleConfig, UseCollapsibleConfig,
UseCollapsibleReturns, UseCollapsibleReturns,
} from './utils/useCollapsible'; } from './components/Collapsible';
export {default as Details} from './components/Details';
export type {DetailsProps} from './components/Details';
export { export {
MobileSecondaryMenuProvider, MobileSecondaryMenuProvider,

View file

@ -0,0 +1,3 @@
<span>Hello {props.name}</span>
This is text some content from `_markdown-partial-example.md`.

View file

@ -1,23 +1,115 @@
--- ---
id: introduction id: introduction
title: Markdown Features introduction title: Markdown Features
sidebar_label: Introduction sidebar_label: Introduction
description: Docusaurus uses GitHub Flavored Markdown (GFM). Find out more about Docusaurus-specific features when writing Markdown. description: Docusaurus uses GitHub Flavored Markdown (GFM). Find out more about Docusaurus-specific features when writing Markdown.
slug: /markdown-features slug: /markdown-features
--- ---
```mdx-code-block
import BrowserWindow from '@site/src/components/BrowserWindow';
```
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. 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. 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. 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 :::important
This section assumes you are using the official Docusaurus content plugins. This section assumes you are using the official Docusaurus content plugins.
::: :::
## Standard features
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.
```md
### My Doc Section
Hello world message with some **bold** text, some _italic_ text and a [link](/)
![img alt](/img/docusaurus.png)
```
```mdx-code-block
<BrowserWindow>
<h2>My Doc Section</h2>
Hello world message with some **bold** text, some _italic_ text and a [link](/)
![img alt](/img/docusaurus.png)
</BrowserWindow>
```
## Quotes
Markdown quotes are beautifully styled:
```md
> This is a quote
```
> This is a quote
## Details
Markdown can embed HTML elements, and [`details`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details) HTML elements are beautifully styled:
```md
### Details element example
<details>
<summary>Toggle me!</summary>
<div>
<div>This is the detailed content</div>
<details>
<summary>
<div>Nested toggle!</div>
<div>Some surprise inside...</div>
</summary>
<div>
😲😲😲😲😲
</div>
</details>
</div>
</details>
```
```mdx-code-block
<BrowserWindow>
<h3>Details element example</h3>
<details>
<summary>Toggle me!</summary>
<div>
<div>This is the detailed content</div>
<details>
<summary>
<div>Nested toggle!</div>
<div>Some surprise inside...</div>
</summary>
<div>
😲😲😲😲😲
</div>
</details>
</div>
</details>
</BrowserWindow>
<br/>
```
:::note
In practice, those are not really HTML elements, but React JSX elements, which we'll cover next!
:::

View file

@ -1,11 +1,13 @@
--- ---
id: react id: react
title: Using React title: MDX and React
description: Using the power of React in Docusaurus Markdown documents, thanks to MDX description: Using the power of React in Docusaurus Markdown documents, thanks to MDX
slug: /markdown-features/react slug: /markdown-features/react
--- ---
```mdx-code-block
import BrowserWindow from '@site/src/components/BrowserWindow'; import BrowserWindow from '@site/src/components/BrowserWindow';
```
## Using JSX in Markdown {#using-jsx-in-markdown} ## Using JSX in Markdown {#using-jsx-in-markdown}
@ -17,6 +19,14 @@ While both `.md` and `.mdx` files are parsed using MDX, some of the syntax are t
::: :::
:::caution
MDX is not [100% compatible with CommonMark](https://github.com/facebook/docusaurus/issues/3018).
Use the **[MDX playground](https://mdxjs.com/playground)** to ensure that your syntax is valid MDX.
:::
Try this block here: Try this block here:
```jsx ```jsx
@ -126,21 +136,27 @@ This feature is experimental and might be subject to API breaking changes in the
## Importing Markdown {#importing-markdown} ## Importing Markdown {#importing-markdown}
You can use Markdown files as components and import them elsewhere, either in Markdown files or in React pages. Below we are importing from [another file](./markdown-features-intro.mdx) and inserting it as a component. You can use Markdown files as components and import them elsewhere, either in Markdown files or in React pages.
```jsx By convention, using the **`_` filename prefix** will not create any doc page and means the markdown file is a **"partial"**, to be imported by other files.
import Intro from './markdown-features-intro.mdx';
<Intro />; ```md title="_markdown-partial-example.mdx"
<span>Hello {props.name}</span>
This is text some content from `_markdown-partial-example.mdx`.
```
```jsx title="someOtherDoc.mdx"
import PartialExample from './_markdown-partial-example.mdx';
<PartialExample name="Sebastien" />;
``` ```
```mdx-code-block ```mdx-code-block
import Intro from './markdown-features-intro.mdx'; import PartialExample from './_markdown-partial-example.mdx';
<BrowserWindow url="http://localhost:3000"> <BrowserWindow url="http://localhost:3000">
<PartialExample name="Sebastien" />
<Intro />
</BrowserWindow> </BrowserWindow>
<br /> <br />