Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion apps/storybook/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
"dependencies": {
"@fortawesome/free-solid-svg-icons": "^6.4.0",
"@fortawesome/react-fontawesome": "^0.2.0",
"@learnn/designn": "workspace:*"
"@learnn/designn": "workspace:*",
"zod": "^3.23.8"
},
"devDependencies": {
"@babel/core": "7.21.4",
Expand Down
276 changes: 276 additions & 0 deletions apps/storybook/stories/RenderMarkdownWithComponents.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,276 @@
import { z } from 'zod'
import {
AppShell,
Button,
defaultTheme,
RenderMarkdownWithComponents,
defineMarkdownComponent,
defineMarkdownComponents,
} from '@learnn/designn'
import { ComponentMeta, ComponentStory } from '@storybook/react'
import React from 'react'

export default {
title: 'Components/RenderMarkdownWithComponents',
component: RenderMarkdownWithComponents,
} as ComponentMeta<typeof RenderMarkdownWithComponents>

function bind(node: JSX.Element) {
const template: ComponentStory<typeof RenderMarkdownWithComponents> = () => node
return template.bind({})
}

const HighlightBox: React.FC<{ color?: string; children?: React.ReactNode }> = ({
color = 'yellow',
children,
}) => {
return (
<div
style={{
backgroundColor: color === 'yellow' ? '#fff9c4' : '#c8e6c9',
padding: '12px',
borderRadius: '8px',
margin: '16px 0',
border: `2px solid ${color === 'yellow' ? '#fdd835' : '#66bb6a'}`,
}}
>
{children}
</div>
)
}

const MARKDOWN_WITHOUT_COMPONENTS = `
# Main Title

This is an example paragraph with **bold** and *italic* text.

## Subtitle

- Bullet point
- Another item
- Third item

\`\`\`javascript
console.log('Example code');
\`\`\`
`

export const MarkdownWithoutComponents = bind(
<AppShell theme={defaultTheme}>
<div style={{ maxWidth: '700px', margin: '0 auto', padding: '20px' }}>
<RenderMarkdownWithComponents components={[]}>
{MARKDOWN_WITHOUT_COMPONENTS}
</RenderMarkdownWithComponents>
</div>
</AppShell>,
)

MarkdownWithoutComponents.storyName = 'Markdown without components'

const buttonComponent = defineMarkdownComponent({
tag: 'button',
props: z.object({
variant: z.union([z.literal('primary'), z.literal('secondary'), z.literal('tertiary')]),
}),
component: ({ variant }) => (
<Button variant={variant} label="Click here" onPress={() => alert('Clicked!')} />
),
})

const MARKDOWN_WITH_ONE_PROP = `
# Example with Button

This is a normal paragraph.

<button variant="primary" />

Here's another paragraph after the component.
`

export const MarkdownWithOneProp = bind(
<AppShell theme={defaultTheme}>
<div style={{ maxWidth: '700px', margin: '0 auto', padding: '20px' }}>
<RenderMarkdownWithComponents components={defineMarkdownComponents(buttonComponent)}>
{MARKDOWN_WITH_ONE_PROP}
</RenderMarkdownWithComponents>
</div>
</AppShell>,
)

MarkdownWithOneProp.storyName = 'Markdown with component and one prop'

const buttonWithSizeComponent = defineMarkdownComponent({
tag: 'button',
props: z.object({
variant: z.union([z.literal('primary'), z.literal('secondary'), z.literal('tertiary')]),
size: z.union([z.literal('sm'), z.literal('md'), z.literal('lg')]),
}),
component: ({ variant, size }) => (
<Button variant={variant} size={size} label="Large button" onPress={() => alert('Clicked!')} />
),
})

const MARKDOWN_WITH_TWO_PROPS = `
# Example with Button and two props

This is a normal paragraph.

<button variant="secondary" size="lg" />

Here's another paragraph after the component.
`

export const MarkdownWithTwoProps = bind(
<AppShell theme={defaultTheme}>
<div style={{ maxWidth: '700px', margin: '0 auto', padding: '20px' }}>
<RenderMarkdownWithComponents components={defineMarkdownComponents(buttonWithSizeComponent)}>
{MARKDOWN_WITH_TWO_PROPS}
</RenderMarkdownWithComponents>
</div>
</AppShell>,
)

MarkdownWithTwoProps.storyName = 'Markdown with component and two props'

const MARKDOWN_WITH_INVALID_PROPS = `
# Example with invalid props

This is a normal paragraph.

<button variant="invalid" />

This tag will not be validated and will be displayed as normal text.

<button variant="primary" invalidProp="test" />

This one also won't be validated because it has an unexpected prop.
`

export const MarkdownWithInvalidProps = bind(
<AppShell theme={defaultTheme}>
<div style={{ maxWidth: '700px', margin: '0 auto', padding: '20px' }}>
<RenderMarkdownWithComponents components={defineMarkdownComponents(buttonComponent)}>
{MARKDOWN_WITH_INVALID_PROPS}
</RenderMarkdownWithComponents>
</div>
</AppShell>,
)

MarkdownWithInvalidProps.storyName = 'Markdown with component with invalid props'

const MARKDOWN_WITH_VALID_AND_INVALID_PROPS = `
# Example with valid and invalid props

This is a normal paragraph.

<button variant="primary" />

This component will be rendered correctly.

<button variant="invalid" />

This one won't be validated and will be displayed as text.

<button variant="secondary" />

And this one will be rendered correctly.
`

export const MarkdownWithValidAndInvalidProps = bind(
<AppShell theme={defaultTheme}>
<div style={{ maxWidth: '700px', margin: '0 auto', padding: '20px' }}>
<RenderMarkdownWithComponents components={defineMarkdownComponents(buttonComponent)}>
{MARKDOWN_WITH_VALID_AND_INVALID_PROPS}
</RenderMarkdownWithComponents>
</div>
</AppShell>,
)

MarkdownWithValidAndInvalidProps.storyName = 'Markdown with component with both valid and invalid props'

const highlightComponent = defineMarkdownComponent({
tag: 'highlight',
props: z.object({
color: z.union([z.literal('yellow'), z.literal('green')]),
}),
component: ({ color, children }) => (
<HighlightBox color={color}>
<RenderMarkdownWithComponents components={[]}>{children || ''}</RenderMarkdownWithComponents>
</HighlightBox>
),
})

const MARKDOWN_WITH_CHILDREN = `
# Example with component and children

This is a normal paragraph.

<highlight color="yellow">
This is the content inside the highlight component. It can contain **markdown** and *formatting*.
</highlight>

Another normal paragraph.

<highlight color="green">
This is another highlight with green color. It can also contain lists:
- Item 1
- Item 2
- Item 3
</highlight>

Final paragraph.
`

export const MarkdownWithChildren = bind(
<AppShell theme={defaultTheme}>
<div style={{ maxWidth: '700px', margin: '0 auto', padding: '20px' }}>
<RenderMarkdownWithComponents components={defineMarkdownComponents(highlightComponent)}>
{MARKDOWN_WITH_CHILDREN}
</RenderMarkdownWithComponents>
</div>
</AppShell>,
)

MarkdownWithChildren.storyName = 'Markdown with component that requires children'

const MARKDOWN_WITH_TWO_COMPONENTS = `
# Example with two different components

This is a normal paragraph with some text.

<button variant="primary" />

Here's some more text between components.

<highlight color="yellow">
This is a highlight box with **bold text** and *italic text*.
</highlight>

Another paragraph with regular text.

<button variant="secondary" />

<highlight color="green">
This is another highlight with a different color. It can contain:
- Lists
- **Formatted text**
- Multiple lines
</highlight>

Final paragraph to show text after components.
`

export const MarkdownWithTwoComponents = bind(
<AppShell theme={defaultTheme}>
<div style={{ maxWidth: '700px', margin: '0 auto', padding: '20px' }}>
<RenderMarkdownWithComponents
components={defineMarkdownComponents(buttonComponent, highlightComponent)}
>
{MARKDOWN_WITH_TWO_COMPONENTS}
</RenderMarkdownWithComponents>
</div>
</AppShell>,
)

MarkdownWithTwoComponents.storyName = 'Markdown with two different components'

7 changes: 4 additions & 3 deletions packages/designn/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@
"remark-gfm": "^1.0.0",
"styled-components": "6.1.8",
"styled-system": "^5.1.5",
"use-places-autocomplete": "^4.0.1"
"use-places-autocomplete": "^4.0.1",
"zod": "^3.23.8"
},
"devDependencies": {
"@babel/preset-env": "7.21.4",
Expand All @@ -55,6 +56,7 @@
"@testing-library/react-hooks": "8.0.1",
"@testing-library/user-event": "14.4.3",
"@types/jest": "29.5.1",
"@types/node": "^18.0.0",
"@types/react": "^18.0.33",
"@types/react-dom": "18.2.1",
"@types/testing-library__jest-dom": "5.14.5",
Expand All @@ -67,8 +69,7 @@
"lint-staged": "13.1.2",
"ts-jest": "29.0.5",
"tsup": "6.5.0",
"typescript": "4.9.5",
"@types/node": "^18.0.0"
"typescript": "4.9.5"
},
"peerDependencies": {
"react": "^17.0.0 || ^18.0.0"
Expand Down
2 changes: 1 addition & 1 deletion packages/designn/src/components/FormattedMarkdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import remarkGfm from 'remark-gfm'
import React from 'react'
import { useState } from 'react'

export type FormattedMarkdownSize = 'sm' | 'xs'
export type FormattedMarkdownSize = 'md' | 'sm' | 'xs'
export type FormattedMarkdownColorVariants = 'primary' | 'secondary'

type MarkdownOverrides = {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import * as React from 'react'
import { z } from 'zod'
import { componentSplitter } from './splitter'
import { FormattedMarkdown, FormattedMarkdownProps, FormattedMarkdownSize } from '../FormattedMarkdown'

type AnyZod = z.ZodTypeAny
type SchemaProps<S extends AnyZod> = z.infer<S>

type WithMarkdownChildren<P> = P & { children?: string }

export type MarkdownComponentConfig<Tag extends string, S extends AnyZod> = {
tag: Tag
props: S
component: React.ComponentType<WithMarkdownChildren<SchemaProps<S>>>
}

export function defineMarkdownComponent<Tag extends string, S extends AnyZod>(
cfg: MarkdownComponentConfig<Tag, S>,
): MarkdownComponentConfig<Tag, S> {
return cfg
}

export function defineMarkdownComponents<Cs extends readonly MarkdownComponentConfig<string, AnyZod>[]>(
...components: Cs
): Cs {
return components
}

export type RenderMarkdownWithComponentsProps<
Cs extends readonly MarkdownComponentConfig<string, AnyZod>[],
> = {
components: Cs
children: string
size?: FormattedMarkdownSize
}

export function RenderMarkdownWithComponents<
Cs extends readonly MarkdownComponentConfig<string, AnyZod>[],
>({ children, components, size = 'sm', ...formattedMarkdownProps }: RenderMarkdownWithComponentsProps<Cs> & FormattedMarkdownProps) {
const parts = componentSplitter(children, [...components])

return (
<>
{parts.map((part, index) => {
if (part.type === 'text') {
return (
<FormattedMarkdown key={index} size={size} {...formattedMarkdownProps}>
{part.content}
</FormattedMarkdown>
)
} else if (part.type === 'component') {
const config = components[part.componentIndex]
if (!config) {
return (
<FormattedMarkdown key={index} size={size} {...formattedMarkdownProps}>
{part.children || ''}
</FormattedMarkdown>
)
}

const Component = config.component
const props = { ...(part.props as Record<string, unknown>), children: part.children }
return React.createElement(Component as React.ComponentType<any>, { key: index, ...props })
}
return null
})}
</>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export { RenderMarkdownWithComponents, defineMarkdownComponent, defineMarkdownComponents } from './RenderMarkdownWithComponents'
export type { MarkdownComponentConfig, RenderMarkdownWithComponentsProps } from './RenderMarkdownWithComponents'
export type { ComponentConfig, Part } from './splitter'
export { componentSplitter } from './splitter'
export { extractAttributesFromXmlTag, extractChildrenFromXmlTag, validateProps } from './utils'
Loading