From e3fc8636578b2a511c64b157fbb0308ac15c0f81 Mon Sep 17 00:00:00 2001 From: Jerel Miller Date: Wed, 3 Jun 2020 15:52:01 -0700 Subject: [PATCH] feat: Add a useComponentDoc hook. Update ReferenceTemplate to use it --- src/hooks/useComponentDoc.js | 30 ++++++++++++++++++ src/templates/ReferenceTemplate.js | 50 +++++++++++++----------------- 2 files changed, 52 insertions(+), 28 deletions(-) create mode 100644 src/hooks/useComponentDoc.js diff --git a/src/hooks/useComponentDoc.js b/src/hooks/useComponentDoc.js new file mode 100644 index 000000000..45369a939 --- /dev/null +++ b/src/hooks/useComponentDoc.js @@ -0,0 +1,30 @@ +import { useMemo } from 'react'; + +const IGNORED_METHODS = [ + 'prototype', + 'length', + 'name', + 'propTypes', + 'getDerivedStateFromProps', + 'defaultProps', +]; + +const useComponentDoc = (componentName) => { + if (typeof window === 'undefined') global.window = {}; + + return useMemo(() => { + const component = window?.__NR1_SDK__?.default?.[componentName]; + + return { + description: component?.__docs__.text, + examples: component?.__docs__.tags.examples ?? [], + methods: Object.getOwnPropertyNames(component).filter( + (member) => + !IGNORED_METHODS.includes(member) && + typeof component[member] === 'function' + ), + }; + }, [componentName, window?.__NR1_SDK__]); +}; + +export default useComponentDoc; diff --git a/src/templates/ReferenceTemplate.js b/src/templates/ReferenceTemplate.js index a7d723661..4f85c8aec 100644 --- a/src/templates/ReferenceTemplate.js +++ b/src/templates/ReferenceTemplate.js @@ -8,10 +8,9 @@ import ComponentExample from '../components/ComponentExample'; import Layout from '../components/Layout'; import Sidebar from '../components/Sidebar'; import SEO from '../components/Seo'; - import pages from '../data/sidenav.json'; - import styles from './ReferenceTemplate.module.scss'; +import useComponentDoc from '../hooks/useComponentDoc'; const previewStyles = { Spinner: { @@ -24,10 +23,9 @@ const ReferenceTemplate = ({ data }) => { const { mdx } = data; const { frontmatter } = mdx; const { title, description, component } = frontmatter; - - if (typeof window === 'undefined') global.window = {}; - const componentData = window?.__NR1_SDK__?.default?.[component]; - const examples = componentData?.__docs__.tags.examples || []; + const { examples, description: componentDescription } = useComponentDoc( + component + ); return ( @@ -42,28 +40,24 @@ const ReferenceTemplate = ({ data }) => {

{component}

- {componentData && componentData.__docs__ && ( - <> -
- -
- {examples.length > 0 && ( -
-

Examples

-
- {examples.map((example, i) => ( - - ))} -
-
- )} - +
+ +
+ {examples.length > 0 && ( +
+

Examples

+
+ {examples.map((example, i) => ( + + ))} +
+
)}