@mdx-js/react#MDXProvider TypeScript Examples
The following examples show how to use
@mdx-js/react#MDXProvider.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.tsx From questdb.io with Apache License 2.0 | 6 votes |
MDXPage = (props: Props) => {
const { content: MDXPageContent } = props
const { frontMatter, metadata } = MDXPageContent
const { title, description, wrapperClassName } = frontMatter
const { permalink } = metadata
return (
<Layout
title={title}
description={description}
permalink={permalink}
wrapperClassName={clsx("container", "row", wrapperClassName)}
>
<main className="col col--8 col--offset-2">
<div className="lg padding-vert--lg">
<MDXProvider components={MDXComponents}>
<MDXPageContent />
</MDXProvider>
</div>
</main>
</Layout>
)
}
Example #2
Source File: _app.tsx From aljoseph.co with MIT License | 6 votes |
function MyApp({ Component, pageProps }: AppProps) {
return (
<ThemeProvider attribute="class">
<MDXProvider components={MDXComponents}>
<Component {...pageProps} />
</MDXProvider>
</ThemeProvider>
);
}
Example #3
Source File: Citation.tsx From nextclade with MIT License | 6 votes |
export function Citation() {
return (
<Container>
<Row noGutters>
<Col>
<MDXProvider components={components}>
<CitationMd />
</MDXProvider>
</Col>
</Row>
</Container>
)
}
Example #4
Source File: _app.tsx From roamjs-com with MIT License | 6 votes |
MDXProviderWrapper: React.FunctionComponent<{ pathname: string }> = ({
pathname,
children,
}) => {
return pathname === "/extensions/[id]" ? (
<>{children}</>
) : (
<MDXProvider components={components}>{children}</MDXProvider>
);
}
Example #5
Source File: mdxRenderer.tsx From usehooks-ts with MIT License | 5 votes |
MdxRenderer = ({ body }: { body: string }) => {
return (
<MDXProvider
components={{
// Typography
h1: props => (
<Title gutterBottom variant="h2" component="h1" {...props} />
),
h2: props => (
<Title gutterBottom variant="h3" component="h2" {...props} />
),
h3: props => (
<Title gutterBottom variant="h4" component="h3" {...props} />
),
h4: props => (
<Title gutterBottom variant="h5" component="h4" {...props} />
),
h5: props => (
<Title gutterBottom variant="h6" component="h5" {...props} />
),
h6: props => (
<Title gutterBottom variant="h6" component="h6" {...props} />
),
a: props => <Link {...props} underline="hover" />,
p: props => <Typography gutterBottom variant="body1" {...props} />,
blockquote: (props: TypographyProps) => (
<Quote variant="body1" {...props} />
),
// Code
pre: props => <Fragment {...props} />,
code: (props: HTMLProps<HTMLElement>) => {
// Extract code language
let lang = undefined
if (
props.hasOwnProperty('className') &&
typeof props.className !== 'undefined'
) {
const classes = props.className.split(' ')
classes.forEach((element: string) => {
if (element.includes('language')) {
lang = element.split('-')[1]
}
})
}
return (
<Code code={childrenToString(props.children)} language={lang} />
)
},
inlineCode: props => (
<InlineCode
gutterBottom
variant="body2"
component="code"
{...props}
/>
),
// Lists
li: props => <Typography variant="body1" component="li" {...props} />,
// Tables
table: props => (
<TableContainer as={Paper}>
<Table {...props} />
</TableContainer>
),
tr: props => <TableRow {...props} />,
td: props => <TableCell {...props} align="left" />,
th: props => <TableCell {...props} align="left" />,
// Mixins
hr: () => <Divider />,
thematicBreak: () => <Divider />,
}}
>
<MDXRenderer>{body}</MDXRenderer>
</MDXProvider>
)
}
Example #6
Source File: guide.tsx From good-arduino-code with MIT License | 5 votes |
/* eslint-disable react/display-name */
export default function GuidesPage({ children, frontMatter }: ILayoutProps) {
const router = useRouter();
if (router.query.thumb) {
return <GuidesThumbnail frontMatter={frontMatter} />;
}
const ogImage =
frontMatter.ogImage ??
`https://thumbs.wokwi.com/api/render.png?service=goodarduinocode&path=${encodeURIComponent(
router.pathname,
)}?thumb=1`;
return (
<MDXProvider
components={{
pre: PreElement,
code: CodeElement,
h1: (props) => <AutolinkedHeading size="h1" {...props} />,
h2: (props) => <AutolinkedHeading size="h2" {...props} />,
h3: (props) => <AutolinkedHeading size="h3" {...props} />,
h4: (props) => <AutolinkedHeading size="h4" {...props} />,
h5: (props) => <AutolinkedHeading size="h5" {...props} />,
h6: (props) => <AutolinkedHeading size="h6" {...props} />,
}}
>
<Head>
<title>{frontMatter.title}</title>
<meta name="description" content={frontMatter.description || ''} />
<meta property="og:site_name" content="Good Arduino Code" />
<meta property="og:title" content={frontMatter.title} />
<meta property="og:description" content={frontMatter.description || ''} />
<meta property="og:image" content={ogImage} />
<meta property="og:image:type" content="image/png" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<meta property="article:publisher" content="https://www.facebook.com/Wokwi" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site" content="@WokwiMakes" />
</Head>
<GlobalStyles />
<Header />
<article className={styles.guide}>
<h1>{frontMatter.title}</h1>
<div className={styles.topBar}>
{frontMatter.readingTime.text}
<SharingButtons />
</div>
{children}
<SharingButtons />
</article>
</MDXProvider>
);
}
Example #7
Source File: index.tsx From questdb.io with Apache License 2.0 | 5 votes |
function TutorialPostItem({
children,
frontMatter,
metadata,
isExternal = false,
isTutorialPage = false,
}: Props) {
const { permalink } = metadata
const { content, description, title, image } = frontMatter
const imageUrl = useBaseUrl(image ?? "/img/tutorial/placeholder.png")
if (isTutorialPage) {
return (
<Button
className={clsx(styles.article)}
variant="plain"
{...{
href: isExternal ? permalink : undefined,
to: isExternal ? undefined : permalink,
}}
uppercase={false}
>
<img
alt={title}
className={clsx(styles.article__image)}
src={imageUrl}
/>
<span className={clsx(styles.article__content)}>
<header>
<h2 className={clsx("margin-bottom--sm", styles.title)}>{title}</h2>
</header>
<section className="markdown">
<MDXProvider components={MDXComponents}>
{isExternal ? content : description}
</MDXProvider>
</section>
</span>
</Button>
)
}
return (
<article className="margin-bottom--xl">
<header>
<h1 className="margin-bottom--sm">{title}</h1>
</header>
<section className="markdown">
<MDXProvider components={MDXComponents}>{children}</MDXProvider>
</section>
</article>
)
}
Example #8
Source File: _app.tsx From nextclade with MIT License | 5 votes |
export function MyApp({ Component, pageProps, router }: AppProps) {
const queryClient = useMemo(() => new QueryClient(), [])
const { store } = useMemo(() => configureStore(), [])
const fallback = useMemo(() => <Loading />, [])
useEffect(() => {
if (process.env.NODE_ENV !== 'development' && router.pathname === '/results') {
void router.replace('/') // eslint-disable-line no-void
}
void router.prefetch('/') // eslint-disable-line no-void
void router.prefetch('/results') // eslint-disable-line no-void
}, [router])
return (
<Suspense fallback={fallback}>
<ReactReduxProvider store={store}>
<RecoilRoot>
<ThemeProvider theme={theme}>
<MDXProvider components={mdxComponents}>
<Plausible domain={DOMAIN_STRIPPED} />
<QueryClientProvider client={queryClient}>
<I18nextProvider i18n={i18n}>
<ErrorBoundary>
<Suspense>
<RecoilStateInitializer />
</Suspense>
<Suspense fallback={fallback}>
<SEO />
<Component {...pageProps} />
<ErrorPopup />
<ReactQueryDevtools initialIsOpen={false} />
</Suspense>
</ErrorBoundary>
</I18nextProvider>
</QueryClientProvider>
</MDXProvider>
</ThemeProvider>
</RecoilRoot>
</ReactReduxProvider>
</Suspense>
)
}
Example #9
Source File: WhatsNewButton.tsx From nextclade with MIT License | 5 votes |
export function WhatsNewButton() {
const { t } = useTranslation()
const [showChangelog, setShowChangelog] = useRecoilState(changelogIsShownAtom)
const [showChangelogOnUpdate, setShowChangelogOnUpdate] = useRecoilState(changelogShouldShowOnUpdatesAtom)
const toggleOpen = useCallback(() => {
setShowChangelog((showChangelog) => !showChangelog)
}, [setShowChangelog])
const open = useCallback(() => {
setShowChangelog(true)
}, [setShowChangelog])
const close = useCallback(() => {
setShowChangelog(false)
}, [setShowChangelog])
const text = t("What's new")
const closeText = t('Close this window')
return (
<>
<ButtonWhatsNewBase type="button" onClick={open} title={text}>
<FaListUl className="mr-xl-2" />
<span className="d-none d-xl-inline">{text}</span>
</ButtonWhatsNewBase>
<Modal centered isOpen={showChangelog} toggle={toggleOpen} fade={false} size="lg">
<ModalHeader toggle={close} tag="div">
<H1 className="text-center">{text}</H1>
</ModalHeader>
<ModalBody>
<MDXProvider components={components}>
<Changelog />
</MDXProvider>
</ModalBody>
<ModalFooter>
<Container fluid>
<Row noGutters className="my-2">
<Col className="d-flex w-100">
<div className="ml-auto">
<Toggle
className="m-0"
identifier={'show-whatsnew-again-toggle'}
checked={showChangelogOnUpdate}
onCheckedChanged={setShowChangelogOnUpdate}
>
{t('Show when a new version is available')}
</Toggle>
</div>
</Col>
</Row>
<Row noGutters className="my-2">
<Col className="d-flex w-100">
<ButtonOk className="ml-auto" type="button" color="success" onClick={close} title={closeText}>
{t('OK')}
</ButtonOk>
</Col>
</Row>
</Container>
</ModalFooter>
</Modal>
</>
)
}
Example #10
Source File: About.tsx From nextclade with MIT License | 5 votes |
export function About() {
return (
<MDXProvider components={mdxComponents}>
<AboutContent />
</MDXProvider>
)
}
Example #11
Source File: singlePage.tsx From mswjs.io with MIT License | 5 votes |
DocumentationPage = ({ data, pageContext }) => {
const { page } = data
const categoryPage = pageContext.breadcrumbs[0]
const siteName = 'Mock Service Worker Docs'
const seo = {
title: [page.frontmatter.title, categoryPage?.title]
.filter(Boolean)
.join(' - '),
description:
page.frontmatter.seo?.description || page.frontmatter.description,
}
return (
<DocsLayout
page={page}
navTree={pageContext.navTree}
breadcrumbs={pageContext.breadcrumbs}
contributors={pageContext.contributors}
lastModified={pageContext.lastModified}
>
<Seo
title={seo.title}
titleTemplate={`%s - ${siteName}`}
description={page.frontmatter.description || siteName}
socialDescription={seo.description}
og={{
siteName,
}}
/>
<h1>{page.frontmatter.title}</h1>
{page.frontmatter.description && (
<TextLead>{page.frontmatter.description}</TextLead>
)}
{page.frontmatter.ads !== false && <CarbonAds />}
<MDXProvider components={components}>
<MDXRenderer>{page.body}</MDXRenderer>
</MDXProvider>
</DocsLayout>
)
}
Example #12
Source File: MdxProvider.tsx From mantine with MIT License | 5 votes |
export default function MdxProvider({ children }: { children: React.ReactNode }) {
return <MDXProvider components={components}>{children}</MDXProvider>;
}
Example #13
Source File: PortfolioModal.tsx From MLH-Fellow-Map with MIT License | 5 votes |
// Provide common components here
function PortfolioModal({ fellow }: { fellow: Fellow }) {
return (
<div className="portfolio-page">
{fellow && (
<>
<img
className="modal-profile-image"
src={fellow.profilePictureUrl}
alt={`Profile of ${fellow.name}`}
/>
<div className="heading u-margin-top-lg">{fellow.name}</div>
<div className="subheading">{fellow.bio}</div>
<div className="pod u-margin-top">
«
<span className="modal-pod">
{' '}
{fellow.podId + ' : ' + fellow.podName}{' '}
</span>{' '}
»
</div>
<PortfolioSocialLinks fellow={fellow} />
{fellow.body && (
<div className="portfolio-body">
<MDXProvider components={shortcodes}>
<MDXRenderer>{fellow.body}</MDXRenderer>
</MDXProvider>
</div>
)}
<div>
<img
className="flame-graph"
src={`http://ghchart.rshah.org/${fellow.github}`}
/>
</div>
<div className="u-margin-top u-margin-bottom">
<a
className="u-color-green"
href={
'https://github.com/Korusuke/MLH-Fellow-Map/tree/master/src/profiles'
}
target="_blank"
rel="noreferrer noopener"
>
<svg
fill="#21af90"
height="1.2em"
width="1.2em"
preserveAspectRatio="xMidYMid meet"
viewBox="0 0 40 40"
style={{
marginRight: '0.3em',
verticalAlign: 'sub',
}}
>
<g>
<path d="m34.5 11.7l-3 3.1-6.3-6.3 3.1-3q0.5-0.5 1.2-0.5t1.1 0.5l3.9 3.9q0.5 0.4 0.5 1.1t-0.5 1.2z m-29.5 17.1l18.4-18.5 6.3 6.3-18.4 18.4h-6.3v-6.2z" />
</g>
</svg>
<span className="u-color-green">
Is this you? Edit this page! :)
</span>
</a>
</div>
</>
)}
</div>
);
}
Example #14
Source File: index.tsx From gatsby-project-kb with MIT License | 5 votes |
Topic: React.FC<Props> = ({ file, currentLocation, refWordMdxSlugDict, wikiLinkLabelTemplateFn, showInlineTOC }: Props) => {
let referenceBlock
const { frontmatter, inboundReferences, outboundReferences, tableOfContents } = file.childMdx
const { title, slug } = file.fields
// console.log(
// 'outboundReferences',
// outboundReferences,
// 'inboundReferences',
// inboundReferences,
// slug,
// )
const ProvidedAnchorTag = (anchorProps) => {
// console.log("ProviµdedAnchorTag", anchorProps)
return (
<AnchorTag
{...anchorProps}
currentLocation={currentLocation}
currentSlug={slug}
references={outboundReferences}
wikiLinkLabelTemplateFn={wikiLinkLabelTemplateFn}
refWordMdxSlugDict={refWordMdxSlugDict}
></AnchorTag>
)
}
if (inboundReferences) {
const references = inboundReferences.reduce((acc, ref) => {
if (!ref.referrer.parent?.fields) return acc
const { slug } = ref.referrer.parent?.fields!
acc.push(<LinkReference key={slug} reference={ref}></LinkReference>)
return acc
}, [] as JSX.Element[])
if (references.length > 0) {
referenceBlock = (
<div className="topic__references">
<h2 id="Backlinks">Backlinks</h2>
<div>{references}</div>
</div>
)
}
}
const shouldRenderTitle = !!frontmatter.title
const realTitle = frontmatter.title || title
return (
<div className="topic">
{shouldRenderTitle ? <h1 id={slugify(realTitle)}>{realTitle}</h1> : null}
{showInlineTOC && <InlineTOC tableOfContents={tableOfContents} />}
<MDXProvider components={{ a: ProvidedAnchorTag, ...HEADER_COMPONENTS }}>
<MDXRenderer scope="">{file.childMdx.body}</MDXRenderer>
</MDXProvider>
{referenceBlock}
</div>
)
}
Example #15
Source File: layout.tsx From carlosazaustre.es with MIT License | 5 votes |
Layout = ({ children, className }: LayoutProps) => (
<MDXProvider
components={{ ExternalLink }}
>
<Styled.root data-testid="theme-root">
<Global
styles={css({
"*": {
boxSizing: `inherit`
},
body: {
margin: 0,
padding: 0,
boxSizing: `border-box`,
textRendering: `optimizeLegibility`,
borderTop: `10px solid #FBCF65`
},
"::selection": {
backgroundColor: `secondary`,
color: `white`
},
a: {
transition: `all 0.3s ease-in-out`,
color: `#FFB934` }
})}
/>
<SEO />
<SkipNavLink>Ver contenido</SkipNavLink>
<Container css={css`
background-color: #fff;
margin: 0 auto;
padding: 0.5rem 1.5rem;
margin-top: 1em;
max-width: 1024px;
`}>
<Header />
<div id="skip-nav" css={css({ ...CodeStyles })} className={className}>
{children}
</div>
<Footer />
</Container>
</Styled.root>
</MDXProvider>
)
Example #16
Source File: _app.tsx From norfolkdevelopers-website with MIT License | 5 votes |
function MyApp({ Component, pageProps }: AppProps) {
return (
<MDXProvider components={MDXComponents}>
<Component {...pageProps} />
</MDXProvider>
);
}
Example #17
Source File: PortfolioPage.tsx From MLH-Fellow-Map with MIT License | 5 votes |
// Provide common components here
function PortfolioPage({ fellow }: { fellow: Fellow }) {
return (
<Layout>
<div className="portfolio-page">
<NavigationHeader fellow={fellow} />
{fellow && (
<>
<img
className="profile-image"
src={fellow.profilePictureUrl}
alt={`Profile of ${fellow.name}`}
/>
<div className="heading">{fellow.name}</div>
<div className="subheading">{fellow.bio}</div>
<PortfolioSocialLinks fellow={fellow} />
{fellow.body && (
<div className="portfolio-body">
<MDXProvider components={shortcodes}>
<MDXRenderer>{fellow.body}</MDXRenderer>
</MDXProvider>
</div>
)}
<div className="u-margin-top">
<img
className="flame-graph"
src={`http://ghchart.rshah.org/${fellow.github}`}
/>
</div>
<a
href={
'https://github.com/Korusuke/MLH-Fellow-Map/edit/master/src/profiles'
}
target="_blank"
rel="noreferrer noopener"
>
<div className="u-margin-top u-margin-bottom">
<svg
fill="#21af90"
height="1.2em"
width="1.2em"
preserveAspectRatio="xMidYMid meet"
viewBox="0 0 40 40"
style={{
marginRight: '0.3em',
verticalAlign: 'sub',
}}
>
<g>
<path d="m34.5 11.7l-3 3.1-6.3-6.3 3.1-3q0.5-0.5 1.2-0.5t1.1 0.5l3.9 3.9q0.5 0.4 0.5 1.1t-0.5 1.2z m-29.5 17.1l18.4-18.5 6.3 6.3-18.4 18.4h-6.3v-6.2z" />
</g>
</svg>
<span className="u-color-green">
Is this you? Edit this page! :)
</span>
</div>
</a>
</>
)}
</div>
</Layout>
);
}
Example #18
Source File: AnchorTag.tsx From gatsby-project-kb with MIT License | 4 votes |
AnchorTag = ({
title,
href,
references = [],
withoutLink,
withoutPopup,
currentSlug,
currentLocation,
refWordMdxSlugDict,
wikiLinkLabelTemplateFn,
...restProps
}: Props) => {
// prettier-ignore
const { anchorSlug } = genHrefInfo({ currentSlug, href })
function getSlugByRefWord(title: string) {
if (!refWordMdxSlugDict) return;
if (title in refWordMdxSlugDict) return `/${refWordMdxSlugDict[title]}`
}
let ref: Reference | undefined
ref = references.find((x) => {
const refSlug = x.target.parent?.fields.slug || ''
return (
`/${x.refWord}` === href ||
getSlugByRefWord(title) === refSlug ||
withPrefix(refSlug) === withPrefix(anchorSlug)
)
})
// console.log('ref', ref, 'href', href, 'anchorSlug', anchorSlug, references)
let content
let popupContent
let child
if (ref && ref.target.parent) {
// console.log('reference is', ref, 'withoutLink', withoutLink)
const targetFileNode = ref.target.parent
const fields = ref.target.parent.fields
const mdxBody = ref.target.body
const nestedComponents = {
a(props) {
const {
anchorSlug: nestedAnchorSlug,
isExternalLink: nestedIsExternalLink,
} = genHrefInfo({ currentSlug, href: props.href })
if (nestedIsExternalLink) {
return <a href={props.href}>{props.children}</a>
} else {
let toSlug = nestedAnchorSlug
if (refWordMdxSlugDict) {
// nested content's anchor label will not be replaced with topic title,
// so it can be used to form slug
const maybeSlug = getSlugByRefWord(props.title)
if (maybeSlug) toSlug = maybeSlug
}
return <Link to={toSlug}>{props.children}</Link>
}
},
p(props) {
return <span {...props} />
},
}
content = wikiLinkLabelTemplateFn
? wikiLinkLabelTemplateFn({ refWord: ref.refWord, title: fields.title })
: restProps.children
popupContent = (
<div id={targetFileNode.id} className="anchor-tag__popover with-markdown">
<React.Fragment>
<MDXProvider components={nestedComponents}>
<MDXRenderer>{mdxBody}</MDXRenderer>
</MDXProvider>
</React.Fragment>
</div>
)
child = (
<Link
{...restProps}
to={padHrefWithAnchor(fields.slug, ref.targetAnchor)}
title={title}
>
{content}
</Link>
)
} else {
content = restProps.children
popupContent = <div className="popover no-max-width">{href}</div>
child = (
<a
{...restProps}
href={
!href || (href.indexOf && href.indexOf('#') === 0)
? href
: withPrefix(href)
}
title={title}
/>
)
return child
}
if (withoutLink) {
return <span>{content}</span>
}
if (withoutPopup) {
return child
}
return (
<Tippy
animation="shift-away"
content={popupContent}
maxWidth="none"
interactive
>
{child}
</Tippy>
)
}
Example #19
Source File: _app.tsx From geist-ui with MIT License | 4 votes |
Application: NextPage<AppProps<{}>> = ({ Component, pageProps }) => {
const theme = useTheme()
const [themeType, setThemeType] = useState<string>()
const [customTheme, setCustomTheme] = useState<GeistUIThemes>(theme)
const themeChangeHandle = (theme: GeistUIThemes) => {
setCustomTheme(theme)
setThemeType(theme.type)
}
useEffect(() => {
const theme = window.localStorage.getItem('theme')
if (theme !== 'dark') return
setThemeType('dark')
}, [])
useDomClean()
return (
<>
<Head>
<title>Geist UI - Modern and minimalist React UI library</title>
<meta name="google" content="notranslate" />
<meta name="twitter:creator" content="@echo_witt" />
<meta name="referrer" content="strict-origin" />
<meta property="og:title" content="Geist UI" />
<meta property="og:site_name" content="Geist UI" />
<meta property="og:url" content="https://geist-ui.dev" />
<link rel="dns-prefetch" href="//geist-ui.dev" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="generator" content="Geist UI" />
<meta
name="description"
content="An open-source design system for building modern websites and applications."
/>
<meta
property="og:description"
content="An open-source design system for building modern websites and applications."
/>
<meta
itemProp="image"
property="og:image"
content="https://user-images.githubusercontent.com/11304944/91128466-dfc96c00-e6da-11ea-8b03-a96e6b98667d.png"
/>
<meta
property="og:image"
content="https://user-images.githubusercontent.com/11304944/91128466-dfc96c00-e6da-11ea-8b03-a96e6b98667d.png"
/>
<meta
property="twitter:image"
content="https://user-images.githubusercontent.com/11304944/91128466-dfc96c00-e6da-11ea-8b03-a96e6b98667d.png"
/>
<meta
name="viewport"
content="initial-scale=1, maximum-scale=1, minimum-scale=1, viewport-fit=cover"
/>
</Head>
<GeistProvider themeType={themeType} themes={[customTheme]}>
<CssBaseline />
<ConfigContext
onThemeChange={themeChangeHandle}
onThemeTypeChange={type => setThemeType(type)}>
<Menu />
<Search />
<MDXProvider
components={{
a: HybridLink,
img: Image,
pre: HybridCode,
}}>
<Component {...pageProps} />
</MDXProvider>
</ConfigContext>
<style global jsx>{`
.tag {
color: ${theme.palette.accents_5};
}
.punctuation {
color: ${theme.palette.accents_5};
}
.attr-name {
color: ${theme.palette.accents_6};
}
.attr-value {
color: ${theme.palette.accents_4};
}
.language-javascript {
color: ${theme.palette.accents_4};
}
span.class-name {
color: ${theme.palette.warning};
}
span.maybe-class-name {
color: ${theme.palette.purple};
}
span.token.string {
color: ${theme.palette.accents_5};
}
span.token.comment {
color: ${theme.palette.accents_3};
}
span.keyword {
color: ${theme.palette.success};
}
span.plain-text {
color: ${theme.palette.accents_3};
}
body::-webkit-scrollbar {
width: var(--geist-page-scrollbar-width);
background-color: ${theme.palette.accents_1};
}
body::-webkit-scrollbar-thumb {
background-color: ${theme.palette.accents_2};
border-radius: ${theme.layout.radius};
}
:root {
--geist-page-nav-height: 64px;
--geist-page-scrollbar-width: 4px;
}
`}</style>
</GeistProvider>
</>
)
}
Example #20
Source File: [id].tsx From xstate-catalogue with MIT License | 4 votes |
ShowMachinePage = (props: {
machine: StateMachine<any, any, any>;
mdxDoc: any;
fileText: string;
slug: string;
meta: MetadataItem;
mdxMetadata?: MDXMetadata;
}) => {
const service = useInterpret(props.machine, {
devTools: true,
});
const [hasDismissed, setHasDismissed] = useState<boolean>(
Boolean(localStorage.getItem('REJECTED_1')),
);
const copyToClipboard = useCopyToClipboard({});
const fileTextRef = useRef(null);
useEffect(() => {
// @ts-ignore
const hljs: any = window.hljs;
if (hljs) {
hljs.highlightBlock(fileTextRef.current);
}
}, [fileTextRef, props.fileText]);
return (
<MachineHelpersContext.Provider
value={{ service, metadata: props.mdxMetadata }}
>
<div className="flex justify-center">
<div className="">
{!hasDismissed && (
<div className="flex justify-center mb-16">
<div className="relative max-w-xl p-6 space-y-4 text-gray-600 bg-gray-50">
<div className="flex items-center space-x-3">
<span className="text-3xl">?</span>
<span className="text-xl font-semibold tracking-tighter">
By the way!
</span>
</div>
<p className="text-gray-500 leading-">
You can interact with the state machine in the article below
by pressing on the <Event>EVENT</Event> buttons. They'll show
up as yellow when they can be interacted with.
</p>
<button
className="absolute top-0 right-0 p-2 mb-2 mr-4 text-lg"
onClick={() => {
setHasDismissed(true);
localStorage.setItem('REJECTED_1', 'true');
}}
>
<span className="text-gray-600">✖</span>
</button>
</div>
</div>
)}
<div className="flex">
<SideBar machine={props.machine} />
<div className="p-6 space-y-6">
<div className="space-x-4 text-xs font-medium tracking-tight text-gray-500">
<a
href={`https://github.com/mattpocock/xstate-catalogue/edit/master/lib/machines/${props.slug}.machine.ts`}
className="inline-flex items-center px-2 py-1 pr-1 space-x-2 text-gray-500 border border-gray-200 rounded"
target="_blank"
>
<span>Edit</span>
<GitHub style={{ height: '1rem', width: '1.2rem' }} />
</a>
<a
href={`https://github.com/mattpocock/xstate-catalogue/discussions?discussions_q=${props.meta.title}`}
className="inline-flex items-center px-2 py-1 pr-1 space-x-2 text-gray-500 border border-gray-200 rounded"
target="_blank"
>
<span>Discuss</span>
<GitHub style={{ height: '1rem', width: '1.2rem' }} />
</a>
</div>
<div className="prose lg:prose-lg">
<MDXProvider
components={{
Event,
State,
Action,
Service,
Context,
WholeContext,
}}
>
<props.mdxDoc></props.mdxDoc>
</MDXProvider>
</div>
</div>
</div>
</div>
</div>
<div className="mt-16">
<div className="p-6 xl:p-12 -mb-20 text-gray-100 bg-gray-900">
<div className="container relative max-w-6xl mx-auto">
<pre>
<code ref={fileTextRef} className="lang-ts">
{props.fileText}
</code>
</pre>
<button
className="invisible md:visible absolute top-0 right-0 px-6 py-3 mr-8 font-bold tracking-tight text-gray-100 bg-blue-700 rounded-lg"
onClick={() => {
copyToClipboard(props.fileText);
}}
>
Copy To Clipboard
</button>
</div>
</div>
</div>
</MachineHelpersContext.Provider>
);
}
Example #21
Source File: index.tsx From fower with MIT License | 4 votes |
function DocPageContent({
currentDocRoute,
versionMetadata,
children,
}: DocPageContentProps): JSX.Element {
const { siteConfig, isClient } = useDocusaurusContext()
const { pluginId, permalinkToSidebar, docsSidebars, version } = versionMetadata
const sidebarName = permalinkToSidebar[currentDocRoute.path]
const sidebar = docsSidebars[sidebarName]
const [hiddenSidebarContainer, setHiddenSidebarContainer] = useState(false)
const [hiddenSidebar, setHiddenSidebar] = useState(false)
const toggleSidebar = useCallback(() => {
if (hiddenSidebar) {
setHiddenSidebar(false)
}
setHiddenSidebarContainer(!hiddenSidebarContainer)
}, [hiddenSidebar])
return (
<Layout
key={isClient}
wrapperClassName="main-docs-wrapper"
searchMetadatas={{
version,
tag: docVersionSearchTag(pluginId, version),
}}
>
<div className={styles.docPage}>
{sidebar && (
<div
className={clsx(styles.docSidebarContainer, {
[styles.docSidebarContainerHidden]: hiddenSidebarContainer,
})}
onTransitionEnd={(e) => {
if (!e.currentTarget.classList.contains(styles.docSidebarContainer)) {
return
}
if (hiddenSidebarContainer) {
setHiddenSidebar(true)
}
}}
role="complementary"
>
<DocSidebar
key={
// Reset sidebar state on sidebar changes
// See https://github.com/facebook/docusaurus/issues/3414
sidebarName
}
sidebar={sidebar}
path={currentDocRoute.path}
sidebarCollapsible={siteConfig.themeConfig?.sidebarCollapsible ?? true}
onCollapse={toggleSidebar}
isHidden={hiddenSidebar}
/>
{hiddenSidebar && (
<div
className={styles.collapsedDocSidebar}
title={translate({
id: 'theme.docs.sidebar.expandButtonTitle',
message: 'Expand sidebar',
description:
'The ARIA label and title attribute for expand button of doc sidebar',
})}
aria-label={translate({
id: 'theme.docs.sidebar.expandButtonAriaLabel',
message: 'Expand sidebar',
description:
'The ARIA label and title attribute for expand button of doc sidebar',
})}
tabIndex={0}
role="button"
onKeyDown={toggleSidebar}
onClick={toggleSidebar}
>
<IconArrow className={styles.expandSidebarButtonIcon} />
</div>
)}
</div>
)}
<main
className={clsx(styles.docMainContainer, {
[styles.docMainContainerEnhanced]: hiddenSidebarContainer,
})}
>
<div
className={clsx('doc-container container padding-vert--lg', styles.docItemWrapper, {
[styles.docItemWrapperEnhanced]: hiddenSidebarContainer,
})}
>
<MDXProvider components={MDXComponents}>{children}</MDXProvider>
</div>
</main>
</div>
</Layout>
)
}
Example #22
Source File: index.tsx From gatsby-theme-pristine with Apache License 2.0 | 4 votes |
Layout: React.FC = ({ children }) => { const darkMode = useDarkMode(); const theme = darkMode.value ? darkTheme : lightTheme; const components = { h1: (props: any) => <Typography variant={"h1"} {...props} gutterBottom={true} />, h2: (props: any) => <Typography variant={"h2"} {...props} gutterBottom={true} />, h3: (props: any) => <Typography variant={"h3"} {...props} gutterBottom={true} />, h4: (props: any) => <Typography variant={"h4"} {...props} gutterBottom={true} />, h5: (props: any) => <Typography variant={"h5"} {...props} gutterBottom={true} />, h6: (props: any) => <Typography variant={"h6"} {...props} gutterBottom={true} />, Demo: (props: any) => <h1>This is a demo component</h1>, code: (props: any) => <CodeBlock darkMode={darkMode.value} {...props} />, thematicBreak: (props: any) => <Divider {...props} />, a: (props: any) => <Link {...props} />, table: (props: any) => <Table {...props} style={{ marginBottom: "15px", ...props.style }} />, thead: (props: any) => <TableHead {...props} />, tr: (props: any) => <TableRow {...props} />, tableBody: (props: any) => <TableBody {...props} />, td: (props: any) => { return ( <TableCell> {props.children || ""} </TableCell> ); }, }; const [open, setOpen] = useState(); const data = useStaticQuery(graphql` query LayoutQuery { site { siteMetadata { title description logoUrl primaryColor secondaryColor footerLinks { name link } } } } `); return ( <MDXProvider components={components}> <MuiThemeProvider theme={{ ...theme, palette: { ...theme.palette, primary: { ...theme.palette.primary, main: data.site.siteMetadata.primaryColor, }, secondary: { ...theme.palette.secondary, main: data.site.siteMetadata.secondaryColor, } } }}> <Sidebar open={open} onClose={() => setOpen(false)} /> <AppBar position="fixed" color="default" elevation={0}> <Toolbar> <IconButton onClick={() => setOpen(true)}> <MenuIcon fontSize="small" /> </IconButton> <Grid container alignContent="center" alignItems="center" justify="space-between"> <Grid item container direction="row" xs={5}> <Grid style={{ paddingRight: "5px" }}> <img alt="logo" height="30" style={{ marginTop: "6px", }} src={data.site.siteMetadata.logoUrl} /> </Grid> <Grid style={{ marginTop: "7px" }}> <GatsbyLink to="/" style={{ textDecoration: "none" }}> <Typography color="textSecondary" variant="h6"> {data.site.siteMetadata.title} </Typography> </GatsbyLink> </Grid> </Grid> <Grid item container direction="row" xs={7} justify="flex-end" alignItems="center"> <Hidden only="xs"> <Search /> </Hidden> <Tooltip title={"Toggle Dark Mode"}> <IconButton onClick={darkMode.toggle}> {darkMode.value ? <Brightness3Icon fontSize="small" /> : <WbSunnyIcon fontSize="small" />} </IconButton> </Tooltip> </Grid> </Grid> </Toolbar> </AppBar> <Container> <CssBaseline /> <div style={{ padding: "30px", paddingTop: "64px" }}> {children} <Footer footerLinks={data.site.siteMetadata.footerLinks} /> </div> </Container> </MuiThemeProvider > </MDXProvider > ); }
Example #23
Source File: index.tsx From earl with MIT License | 4 votes |
function DocPageContent({ currentDocRoute, versionMetadata, children }: DocPageContentProps): JSX.Element {
const { pluginId, version } = versionMetadata
const sidebarName = currentDocRoute.sidebar
const sidebar = sidebarName ? versionMetadata.docsSidebars[sidebarName] : undefined
const [hiddenSidebarContainer, setHiddenSidebarContainer] = useState(false)
const [hiddenSidebar, setHiddenSidebar] = useState(false)
const toggleSidebar = useCallback(() => {
if (hiddenSidebar) {
setHiddenSidebar(false)
}
setHiddenSidebarContainer((value) => !value)
}, [hiddenSidebar])
return (
<Layout
wrapperClassName={ThemeClassNames.wrapper.docsPages}
pageClassName={ThemeClassNames.page.docsDocPage}
searchMetadatas={{
version,
tag: docVersionSearchTag(pluginId, version),
}}
>
<div className={styles.docPage}>
<BackToTopButton />
{sidebar && (
<aside
className={clsx(styles.docSidebarContainer, {
[styles.docSidebarContainerHidden]: hiddenSidebarContainer,
})}
onTransitionEnd={(e) => {
if (!e.currentTarget.classList.contains(styles.docSidebarContainer)) {
return
}
if (hiddenSidebarContainer) {
setHiddenSidebar(true)
}
}}
>
<DocSidebar
key={
// Reset sidebar state on sidebar changes
// See https://github.com/facebook/docusaurus/issues/3414
sidebarName
}
sidebar={sidebar}
path={currentDocRoute.path}
onCollapse={toggleSidebar}
isHidden={hiddenSidebar}
/>
{hiddenSidebar && (
<div
className={styles.collapsedDocSidebar}
title={translate({
id: 'theme.docs.sidebar.expandButtonTitle',
message: 'Expand sidebar',
description: 'The ARIA label and title attribute for expand button of doc sidebar',
})}
aria-label={translate({
id: 'theme.docs.sidebar.expandButtonAriaLabel',
message: 'Expand sidebar',
description: 'The ARIA label and title attribute for expand button of doc sidebar',
})}
tabIndex={0}
role="button"
onKeyDown={toggleSidebar}
onClick={toggleSidebar}
>
<IconArrow className={styles.expandSidebarButtonIcon} />
</div>
)}
</aside>
)}
<main
className={clsx(styles.docMainContainer, {
[styles.docMainContainerEnhanced]: hiddenSidebarContainer || !sidebar,
})}
>
<div
className={clsx('container padding-top--lg padding-bottom--lg', styles.docItemWrapper, {
[styles.docItemWrapperEnhanced]: hiddenSidebarContainer,
})}
>
<MDXProvider components={MDXComponents}>{children}</MDXProvider>
</div>
</main>
</div>
</Layout>
)
}
Example #24
Source File: app.tsx From website with Apache License 2.0 | 4 votes |
App = () => {
const location = useLocation();
const pageSlug = location.pathname;
const page = getPage(pageSlug);
return (
<AnchorProvider>
<RootLayout
aside={
page && (
<nav aria-label="page">
<VerticalStack gap={2}>
<Heading look="h500" as="div">
Contents
</Heading>
{page.data.headings
.filter((heading) => heading.depth < 4)
.map((heading, index) => (
<ToAnchor
depth={heading.depth}
key={`${heading.text}-${index}`}>
{heading.text}
</ToAnchor>
))}
</VerticalStack>
</nav>
)
}
sidenav={
<>
{getSections().map((section, sectionIndex) => (
<Section
key={section.name}
title={section.name.replace(/^\d+-/, '')}>
{section.pages.map((page, pageIndex) => (
<LinkItem
aria-current={
location.pathname === `/${page.name}` ||
(location.pathname === '/' &&
sectionIndex === 0 &&
pageIndex === 0)
? 'page'
: undefined
}
href={`/${page.name}`}
key={page.name}>
{page.data.name || titleCase(page.name)}
</LinkItem>
))}
</Section>
))}
</>
}>
<MDXProvider components={mdxComponents}>
<ScrollTop key={pageSlug} />
<PageTitle
title={
(page && page.data.headings[0].text) ||
(page && titleCase(page.name))
}
/>
{page && (
<>
<page.Component />
<p css={{ margin: '8rem 0' }}>
<a
target="_blank"
css={{
textDecoration: 'none',
borderRadius: 3,
color: colors.primary,
fontSize: 14,
opacity: 0.7,
fontWeight: 500,
}}
href={getEditUrl()}>
<Text variant="aside" weight="bold">
Suggest changes to this page ➚
</Text>
</a>
</p>
<div
css={{
margin: '12rem 0 9rem',
display: 'flex',
'[data-next="true"]': {
marginLeft: 'auto',
},
}}>
{page.previous && (
<PageLink
direction="previous"
section={page.previous.cta}
to={`/${page.previous.slug}`}>
{page.previous.name || titleCase(page.previous.slug)}
</PageLink>
)}
{page.next && (
<PageLink
direction="next"
section={page.next.cta}
to={`/${page.next.slug}`}>
{page.next.name || titleCase(page.next.slug)}
</PageLink>
)}
</div>
</>
)}
</MDXProvider>
</RootLayout>
</AnchorProvider>
);
}
Example #25
Source File: layout.tsx From papercups.io with MIT License | 4 votes |
render() {
const {title, width, dark = false, className = '', children} = this.props;
return (
<Flex
className={`flex-auto flex-col min-h-0 ${
dark ? 'dark bg-gray-900' : 'bg-white'
}`}
>
<Head>
<title>
Papercups | {title || 'Open Source Intercom Alternative'}
</title>
<link rel="icon" href="/logo-v2.svg" />
<meta
name="description"
content="Papercups is an open-source live chat widget. Chat with your customers to improve conversions and customer satisfaction."
></meta>
<script
async
src="https://platform.twitter.com/widgets.js"
charSet="utf-8"
></script>
</Head>
<NavMenu dark={dark} />
<main className="flex-auto min-h-0 dark:text-white">
<Box
className={className}
mx="auto"
style={{maxWidth: width || 800}}
pt={5}
px={4}
pb={6}
>
<MDXProvider components={this.state}>{children}</MDXProvider>
</Box>
</main>
<footer className="bg-gray-800 flex-0">
<div
className="max-w-5xl mx-auto px-4"
style={{maxWidth: width || 800}}
>
<Flex py={5} sx={{justifyContent: 'space-between'}}>
<Flex sx={{alignItems: 'center'}}>
<p className="text-white pr-3">
Backed by <b>Y Combinator</b>
</p>
<Image sx={{width: '20px', height: '20px'}} src="yc-logo.png" />
</Flex>
<Box>
<a href="/privacy" className="white_link">
Privacy
</a>
</Box>
</Flex>
</div>
</footer>
{this.isWindowReady() && (
<ChatWidget
token="eb504736-0f20-4978-98ff-1a82ae60b266"
inbox="364b1871-6db5-4bc0-9a88-994e06adbda6"
title="Welcome to Papercups!"
subtitle="Ask us anything in the chat window below ?"
greeting="Hi there! Send us a message and we'll get back to you as soon as we can. In the meantime, check out our [demo](https://app.papercups.io/demo)!"
primaryColor="#1890ff"
iconVariant="filled"
requireEmailUpfront
showAgentAvailability
// Pops up initial message after 2s when `shouldPopUpInitialMessage` return `true`
popUpInitialMessage={
this.shouldPopUpInitialMessage() ? 2000 : false
}
setDefaultGreeting={(settings) => {
const path = window.location.pathname;
switch (path) {
case '/pricing':
return "Hi there! Let us know if you have any questions about pricing :) (we're offering deals to startups and international founders)";
default:
return "Hi there! Send us a message and we'll get back to you as soon as we can. In the meantime, check out our [demo](https://app.papercups.io/demo)!";
}
}}
/>
)}
</Flex>
);
}
Example #26
Source File: index.tsx From website-docs with MIT License | 4 votes |
export default function Doc({
pageContext: { name, availIn, pathConfig, filePath },
data,
}: Props) {
const {
site,
mdx: { frontmatter, tableOfContents, body },
navigation: { navigation },
} = data
const tocData = useMemo(() => {
if (tableOfContents.items!.length === 1) {
return tableOfContents.items![0].items
}
return tableOfContents.items
}, [tableOfContents.items])
const stableBranch = getStable(pathConfig.repo)
const dispatch = useDispatch()
useEffect(() => {
// https://github.com/pingcap/website-docs/issues/221
// md title with html tag will cause anchor mismatch
replaceInternalHref(pathConfig.locale, pathConfig.repo, pathConfig.version)
dispatch(
setDocInfo({
lang: pathConfig.locale,
type: pathConfig.repo,
version: pathConfig.version,
})
)
}, [dispatch, pathConfig])
useCodeBlock()
return (
<Layout locale={availIn.locale}>
<article className="PingCAP-Doc">
<Columns>
<div className="column is-one-fifth">
<div className="left-aside">
{pathConfig.repo !== 'tidbcloud' && (
<VersionSwitcher
name={name}
pathConfig={pathConfig}
availIn={availIn.version}
/>
)}
<Navigation data={navigation} />
</div>
</div>
<Seo
title={frontmatter.title}
description={frontmatter.summary}
meta={[
{
name: 'doc:lang',
content: pathConfig.locale,
},
{
name: 'doc:type',
content: pathConfig.repo,
},
{
name: 'doc:version',
content: pathConfig.branch,
},
]}
link={[
...(pathConfig.branch !== stableBranch && stableBranch != null
? [
{
rel: 'canonical',
href: `${site.siteMetadata.siteUrl}${generateUrl(name, {
...pathConfig,
branch: stableBranch,
})}`,
},
]
: []),
]}
/>
<Column size={7}>
<div className="markdown-body doc-content">
<CustomNotice
name={name}
pathConfig={pathConfig}
availIn={availIn.version}
/>
<MDXProvider components={{ ...Shortcodes, Link }}>
<MDXRenderer>{body}</MDXRenderer>
</MDXProvider>
{pathConfig.repo !== Repo.tidbcloud && (
<GitCommitInfo
pathConfig={pathConfig}
title={frontmatter.title}
filePath={filePath}
/>
)}
</div>
</Column>
<Column>
<div className="right-aside">
<Block>
<DownloadPDF pathConfig={pathConfig} />
{pathConfig.repo !== 'tidbcloud' && (
<>
<FeedbackDoc pathConfig={pathConfig} filePath={filePath} />
{pathConfig.version === 'dev' && (
<Improve pathConfig={pathConfig} filePath={filePath} />
)}
</>
)}
{pathConfig.locale === 'zh' && <TechFeedback />}
</Block>
<div className="doc-toc">
<Title size={6} style={{ marginBottom: 0 }}>
<Trans i18nKey="doc.toc" />
</Title>
{tocData && <Toc data={tocData} />}
</div>
</div>
</Column>
<UserFeedback title={frontmatter.title} locale={pathConfig.locale} />
</Columns>
</article>
</Layout>
)
}
Example #27
Source File: index.tsx From questdb.io with Apache License 2.0 | 4 votes |
DocPage = ({
location,
route: { routes },
versionMetadata,
...rest
}: Props) => {
const { siteConfig, isClient } = useDocusaurusContext()
const { permalinkToSidebar, docsSidebars } = versionMetadata ?? {}
const docRoutes = (routes as unknown) as Routes[]
const currentDocRoute = routes.find((docRoute) =>
matchPath(location.pathname, docRoute),
)
const [hiddenSidebarContainer, setHiddenSidebarContainer] = useState(false)
const [hiddenSidebar, setHiddenSidebar] = useState(false)
const toggleSidebar = useCallback(() => {
if (hiddenSidebar) {
setHiddenSidebar(false)
}
setHiddenSidebarContainer(!hiddenSidebarContainer)
if (
!hiddenSidebar &&
window.matchMedia("(prefers-reduced-motion: reduce)").matches
) {
setHiddenSidebar(true)
}
}, [
hiddenSidebar,
hiddenSidebarContainer,
setHiddenSidebar,
setHiddenSidebarContainer,
])
const handleTransitionEnd = useCallback(
(event: TransitionEvent<HTMLDivElement>) => {
if (!event.currentTarget.classList.contains(styles.docSidebarContainer)) {
return
}
if (hiddenSidebarContainer) {
setHiddenSidebar(true)
}
},
[hiddenSidebarContainer, setHiddenSidebar],
)
if (currentDocRoute == null) {
return <NotFound location={location} {...rest} />
}
const sidebarName = permalinkToSidebar[currentDocRoute.path] as
| string
| undefined
const sidebar = sidebarName != null ? docsSidebars[sidebarName] : []
return (
<Layout
description={customFields.description}
key={isClient.toString()}
title="Introduction"
>
<div className={styles.doc}>
{sidebarName != null && (
<div
className={clsx(styles.doc__sidebar, {
[styles["doc__sidebar--hidden"]]: hiddenSidebarContainer,
})}
onTransitionEnd={handleTransitionEnd}
role="complementary"
>
<DocSidebar
key={
// Reset sidebar state on sidebar changes
// See https://github.com/facebook/docusaurus/issues/3414
sidebarName
}
sidebar={sidebar}
path={currentDocRoute.path}
sidebarCollapsible={
siteConfig.themeConfig?.sidebarCollapsible ?? true
}
onCollapse={toggleSidebar}
isHidden={hiddenSidebar}
/>
{hiddenSidebar && (
<div
className={styles.doc__expand}
title="Expand sidebar"
aria-label="Expand sidebar"
tabIndex={0}
role="button"
onKeyDown={toggleSidebar}
onClick={toggleSidebar}
/>
)}
</div>
)}
<main className={styles.doc__main}>
<div
className={clsx(
"padding-vert--lg",
"container",
styles["doc__item-wrapper"],
{
[styles["doc__item-wrapper--enhanced"]]: hiddenSidebarContainer,
},
)}
>
<MDXProvider components={MDXComponents}>
{renderRoutes(docRoutes)}
</MDXProvider>
</div>
</main>
</div>
</Layout>
)
}
Example #28
Source File: index.tsx From documentation with MIT License | 4 votes |
DocPageContent = (props: DocPageContentProps) => {
const { currentDocRoute, versionMetadata, children, sidebarName } = props;
const { siteConfig } = useDocusaurusContext();
const { pluginId, version } = versionMetadata;
const sidebar = useDocsSidebar();
const [hiddenSidebarContainer, setHiddenSidebarContainer] = useState(false);
const [hiddenSidebar, setHiddenSidebar] = useState(false);
const toggleSidebar = useCallback(() => {
if (hiddenSidebar) {
setHiddenSidebar(false);
}
setHiddenSidebarContainer(!hiddenSidebarContainer);
}, [hiddenSidebar]);
const handleTransitionEnd = useCallback(
(event: TransitionEvent<HTMLDivElement>) => {
if (!event.currentTarget.classList.contains(styles.docSidebarContainer)) {
return;
}
if (hiddenSidebarContainer) {
setHiddenSidebar(true);
}
},
[hiddenSidebarContainer, setHiddenSidebar]
);
return (
<Layout
wrapperClassName="main-docs-wrapper"
searchMetadata={{
version,
tag: docVersionSearchTag(pluginId, version),
}}>
<div className={styles.docPage}>
<BackToTopButton />
{/* Sidebar */}
{sidebar && (
<aside
className={clsx(styles.docSidebarContainer, {
[styles.docSidebarContainerHidden]: hiddenSidebarContainer,
})}
onTransitionEnd={handleTransitionEnd}
role="complementary">
<DocSidebar
key={
// Reset sidebar state on sidebar changes
// See https://github.com/facebook/docusaurus/issues/3414
sidebarName
}
sidebar={sidebar}
path={currentDocRoute.path}
sidebarCollapsible={
siteConfig.themeConfig?.sidebarCollapsible ?? true
}
onCollapse={toggleSidebar}
isHidden={hiddenSidebar}
/>
{hiddenSidebar && (
<div
className={styles.collapsedDocSidebar}
title={translate({
id: 'theme.docs.sidebar.expandButtonTitle',
message: 'Expand sidebar',
description:
'The ARIA label and title attribute for expand button of doc sidebar',
})}
aria-label={translate({
id: 'theme.docs.sidebar.expandButtonAriaLabel',
message: 'Expand sidebar',
description:
'The ARIA label and title attribute for expand button of doc sidebar',
})}
tabIndex={0}
role="button"
onKeyDown={toggleSidebar}
onClick={toggleSidebar}>
<IconArrow className={styles.expandSidebarButtonIcon} />
</div>
)}
</aside>
)}
{/* Doc Content */}
<main
className={clsx(styles.docMainContainer, {
[styles.docMainContainerEnhanced]: hiddenSidebarContainer,
})}>
<div
className={clsx(
'padding-vert--lg',
'container',
styles.docItemWrapper,
{
[styles.docItemWrapperEnhanced]: hiddenSidebarContainer,
}
)}>
<MDXProvider components={MDXComponents}>{children}</MDXProvider>
</div>
</main>
</div>
</Layout>
);
}
Example #29
Source File: DocsPage.tsx From vanilla-extract with MIT License | 4 votes |
DocsPage = ({ location }: RouteChildrenProps) => {
const [menuOpen, setMenuOpen] = useState(false);
const toggleMenu = () => setMenuOpen((open) => !open);
const closeMenu = () => setMenuOpen(false);
const normalisedPath = location.pathname.endsWith('/')
? location.pathname.slice(0, location.pathname.lastIndexOf('/'))
: location.pathname;
useEffect(() => {
if (menuOpen) {
document.body.classList.add(styles.bodyLock);
return () => {
document.body.classList.remove(styles.bodyLock);
};
}
}, [menuOpen]);
return (
<>
<Header />
<MenuBackdrop open={menuOpen} onClick={closeMenu} />
<PrimaryNav
open={menuOpen}
onClick={closeMenu}
pathname={normalisedPath}
/>
<SecondaryNav onClick={closeMenu} pathname={normalisedPath} />
<Box zIndex={1} position="fixed" top={0} right={0} padding="large">
<Box display={{ mobile: 'none', desktop: 'block' }}>
<ColorModeToggle />
</Box>
<Box display={{ desktop: 'none' }}>
<Fab open={menuOpen} onClick={toggleMenu} />
</Box>
</Box>
<Box className={styles.container} zIndex={-1}>
<Box
component="main"
paddingRight="large"
paddingLeft={{ mobile: 'large', desktop: 'xxlarge' }}
paddingTop={{ mobile: 'xxlarge', desktop: 'xlarge' }}
className={styles.main}
>
<ContentBlock>
<Box paddingBottom="xxxlarge">
<MDXProvider components={mdxComponents}>
{docs.map(({ route, Component, title, sections }, index) => {
const prevDoc = docs[index - 1];
const nextDoc = docs[index + 1];
const pageTitle = `${
title ? `${title} — ` : ''
}vanilla-extract`.trim();
const hashes = sections
.filter(({ level }) => level === 2 || level === 3)
.map(({ hash }) => hash);
return (
<Route
key={route}
path={route}
exact
render={() => (
<>
<Title>{pageTitle}</Title>
<Meta property="og:title" content={pageTitle} />
<Meta name="twitter:title" content={pageTitle} />
<DocsRoute
nextDoc={nextDoc}
prevDoc={prevDoc}
hashes={hashes}
component={Component}
/>
</>
)}
/>
);
})}
</MDXProvider>
</Box>
</ContentBlock>
</Box>
</Box>
</>
);
}