Skip to content

Avoid bad hooks dependency usage in MarkdownHooks #891

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
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
7 changes: 6 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,9 @@
* @typedef {import('./lib/index.js').UrlTransform} UrlTransform
*/

export {Markdown as default, defaultUrlTransform} from './lib/index.js'
export {
MarkdownAsync,
MarkdownHooks,
Markdown as default,
defaultUrlTransform
} from './lib/index.js'
234 changes: 209 additions & 25 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
/**
* @import {Element, ElementContent, Nodes, Parents, Root} from 'hast'
* @import {ComponentProps, ElementType, ReactElement} from 'react'
* @import {Root as MdastRoot} from 'mdast'
* @import {ComponentProps, ElementType, ReactElement, ReactNode, RefObject} from 'react'
* @import {Options as RemarkRehypeOptions} from 'remark-rehype'
* @import {BuildVisitor} from 'unist-util-visit'
* @import {PluggableList} from 'unified'
* @import {PluggableList, Processor} from 'unified'
*/

/**
Expand Down Expand Up @@ -91,10 +92,18 @@
* Transformed URL (optional).
*/

/**
* @typedef RefState
* @property {Options} options
* @property {Processor<MdastRoot, MdastRoot, Root, undefined, undefined>} processor
* @property {Promise<Root>} promise
*/

import {unreachable} from 'devlop'
import {toJsxRuntime} from 'hast-util-to-jsx-runtime'
import {urlAttributes} from 'html-url-attributes'
import {Fragment, jsx, jsxs} from 'react/jsx-runtime'
import {use, useRef} from 'react'
import remarkParse from 'remark-parse'
import remarkRehype from 'remark-rehype'
import {unified} from 'unified'
Expand Down Expand Up @@ -149,33 +158,119 @@ const deprecations = [
/**
* Component to render markdown.
*
* This is a synchronous component.
* When using async plugins,
* see {@linkcode MarkdownAsync} or {@linkcode MarkdownHooks}.
*
* @param {Readonly<Options>} options
* Props.
* @returns {ReactElement}
* React element.
*/
export function Markdown(options) {
const allowedElements = options.allowedElements
const allowElement = options.allowElement
const children = options.children || ''
const className = options.className
const components = options.components
const disallowedElements = options.disallowedElements
const processor = createProcessor(options)
const file = createFile(options)
return post(processor.runSync(processor.parse(file), file), options)
}

/**
* Component to render markdown with support for async plugins
* through async/await.
*
* Components returning promises are supported on the server.
* For async support on the client,
* see {@linkcode MarkdownHooks}.
*
* @param {Readonly<Options>} options
* Props.
* @returns {Promise<ReactElement>}
* Promise to a React element.
*/
export async function MarkdownAsync(options) {
const processor = createProcessor(options)
const file = createFile(options)
const tree = await processor.run(processor.parse(file), file)
return post(tree, options)
}

/**
* Component to render markdown with support for async plugins through hooks.
*
* This uses `useEffect` and `useState` hooks.
* Hooks run on the client and do not immediately render something.
* For async support on the server,
* see {@linkcode MarkdownAsync}.
*
* @param {Readonly<Options>} options
* Props.
* @returns {ReactNode}
* React element.
*/
export function MarkdownHooks(options) {
const ref = /** @type {RefObject<RefState>} */ (useRef({}))
const prev = ref.current
let processor = prev.processor

if (
!processor ||
prev.options.remarkRehypeOptions !== options.remarkRehypeOptions ||
arePluggableListsEqual(prev.options.rehypePlugins, options.rehypePlugins) ||
arePluggableListsEqual(prev.options.remarkPlugins, options.remarkPlugins)
) {
processor = createProcessor(options)
}

if (
prev.processor !== processor ||
prev.options.children !== options.children
) {
const file = createFile(options)
prev.processor = processor
prev.promise = processor.run(processor.parse(file), file)
}

const tree = use(prev.promise)

/* c8 ignore next -- hooks are client-only. */
if (tree) {
return post(tree, options)
}
}

/**
* Set up the `unified` processor.
*
* @param {Readonly<Options>} options
* Props.
* @returns {Processor<MdastRoot, MdastRoot, Root, undefined, undefined>}
* Result.
*/
function createProcessor(options) {
const rehypePlugins = options.rehypePlugins || emptyPlugins
const remarkPlugins = options.remarkPlugins || emptyPlugins
const remarkRehypeOptions = options.remarkRehypeOptions
? {...options.remarkRehypeOptions, ...emptyRemarkRehypeOptions}
: emptyRemarkRehypeOptions
const skipHtml = options.skipHtml
const unwrapDisallowed = options.unwrapDisallowed
const urlTransform = options.urlTransform || defaultUrlTransform

const processor = unified()
.use(remarkParse)
.use(remarkPlugins)
.use(remarkRehype, remarkRehypeOptions)
.use(rehypePlugins)

return processor
}

/**
* Set up the virtual file.
*
* @param {Readonly<Options>} options
* Props.
* @returns {VFile}
* Result.
*/
function createFile(options) {
const children = options.children || ''
const file = new VFile()

if (typeof children === 'string') {
Expand All @@ -188,11 +283,27 @@ export function Markdown(options) {
)
}

if (allowedElements && disallowedElements) {
unreachable(
'Unexpected combined `allowedElements` and `disallowedElements`, expected one or the other'
)
}
return file
}

/**
* Process the result from unified some more.
*
* @param {Nodes} tree
* Tree.
* @param {Readonly<Options>} options
* Props.
* @returns {ReactElement}
* React element.
*/
function post(tree, options) {
const allowedElements = options.allowedElements
const allowElement = options.allowElement
const components = options.components
const disallowedElements = options.disallowedElements
const skipHtml = options.skipHtml
const unwrapDisallowed = options.unwrapDisallowed
const urlTransform = options.urlTransform || defaultUrlTransform

for (const deprecation of deprecations) {
if (Object.hasOwn(options, deprecation.from)) {
Expand All @@ -212,26 +323,28 @@ export function Markdown(options) {
}
}

const mdastTree = processor.parse(file)
/** @type {Nodes} */
let hastTree = processor.runSync(mdastTree, file)
if (allowedElements && disallowedElements) {
unreachable(
'Unexpected combined `allowedElements` and `disallowedElements`, expected one or the other'
)
}

// Wrap in `div` if there’s a class name.
if (className) {
hastTree = {
if (options.className) {
tree = {
type: 'element',
tagName: 'div',
properties: {className},
properties: {className: options.className},
// Assume no doctypes.
children: /** @type {Array<ElementContent>} */ (
hastTree.type === 'root' ? hastTree.children : [hastTree]
tree.type === 'root' ? tree.children : [tree]
)
}
}

visit(hastTree, transform)
visit(tree, transform)

return toJsxRuntime(hastTree, {
return toJsxRuntime(tree, {
Fragment,
// @ts-expect-error
// React components are allowed to return numbers,
Expand Down Expand Up @@ -331,3 +444,74 @@ export function defaultUrlTransform(value) {

return ''
}

/**
* Check if two unified pluggable lists are equal.
*
* Pluggable lists are considered equal if:
* - Both are empty or nullish.
* - Both contain the same plugins with the same options.
*
* @param {PluggableList | null | undefined} oldList
* The pluggable list that was passed in the last React render call.
* @param {PluggableList | null | undefined} newList
* The pluggable list that was passed in the new React render call.
* @returns {boolean}
* Whether or not the pluggable lists are equal.
*/
function arePluggableListsEqual(oldList, newList) {
if (oldList === newList) {
return true
}

// Consider nullish or empty pluggable lists equal.
if (!oldList?.length) {
return !newList?.length
}

if (!newList?.length) {
return false
}

if (oldList.length !== newList.length) {
return false
}

for (let index = 0; index < oldList.length; index++) {
let oldPluggable = oldList[index]
let newPluggable = newList[index]

if (oldPluggable === newPluggable) {
continue
}

/** @type {unknown} */
let oldOptions
/** @type {unknown} */
let newOptions

// It’s a tuple. Unwrap it.
if (Array.isArray(oldPluggable)) {
// Consider null and undefined options equal
oldOptions = oldPluggable[1] ?? undefined
oldPluggable = oldPluggable[0]
}

// It’s a tuple. Unwrap it.
if (Array.isArray(newPluggable)) {
// Consider null and undefined options equal
newOptions = newPluggable[1] ?? undefined
newPluggable = newPluggable[0] ?? undefined
}

if (oldPluggable !== newPluggable) {
return false
}

if (oldOptions !== newOptions) {
return false
}
}

return false
}
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
],
"dependencies": {
"@types/hast": "^3.0.0",
"@types/mdast": "^4.0.0",
"devlop": "^1.0.0",
"hast-util-to-jsx-runtime": "^2.0.0",
"html-url-attributes": "^3.0.0",
Expand All @@ -65,12 +66,14 @@
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"c8": "^10.0.0",
"concat-stream": "^2.0.0",
"esbuild": "^0.25.0",
"eslint-plugin-react": "^7.0.0",
"prettier": "^3.0.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"rehype-raw": "^7.0.0",
"rehype-starry-night": "^2.0.0",
"remark-cli": "^12.0.0",
"remark-gfm": "^4.0.0",
"remark-preset-wooorm": "^11.0.0",
Expand Down
Loading
Loading