feat: allowing specifying the content of ReacNodeViewContent via a React Context

This commit is contained in:
Nick the Sick 2024-08-20 17:30:37 +02:00
parent 4b2de3394a
commit a06fe0b9e4
No known key found for this signature in database
GPG Key ID: F575992F156E5BCC
2 changed files with 24 additions and 12 deletions

View File

@ -1,15 +1,14 @@
import React from 'react'
import React, { ComponentProps } from 'react'
import { useReactNodeView } from './useReactNodeView.js'
export interface NodeViewContentProps {
[key: string]: any,
as?: React.ElementType,
}
export type NodeViewContentProps<T extends keyof React.JSX.IntrinsicElements = 'div'> = {
// eslint-disable-next-line no-undef
as?: NoInfer<T>;
} & ComponentProps<T>
export const NodeViewContent: React.FC<NodeViewContentProps> = props => {
const Tag = props.as || 'div'
const { nodeViewContentRef } = useReactNodeView()
export function NodeViewContent<T extends keyof React.JSX.IntrinsicElements = 'div'>({ as: Tag = 'div', ...props }: NodeViewContentProps<T>) {
const { nodeViewContentRef, nodeViewContentChildren } = useReactNodeView()
return (
// @ts-ignore
@ -21,6 +20,8 @@ export const NodeViewContent: React.FC<NodeViewContentProps> = props => {
whiteSpace: 'pre-wrap',
...props.style,
}}
/>
>
{nodeViewContentChildren}
</Tag>
)
}

View File

@ -1,12 +1,23 @@
import { createContext, useContext } from 'react'
import { createContext, ReactNode, useContext } from 'react'
export interface ReactNodeViewContextProps {
onDragStart: (event: DragEvent) => void,
nodeViewContentRef: (element: HTMLElement | null) => void,
/**
* This allows you to add children into the NodeViewContent component.
* This is useful when statically rendering the content of a node view.
*/
nodeViewContentChildren: ReactNode,
}
export const ReactNodeViewContext = createContext<Partial<ReactNodeViewContextProps>>({
onDragStart: undefined,
export const ReactNodeViewContext = createContext<ReactNodeViewContextProps>({
onDragStart: () => {
// no-op
},
nodeViewContentChildren: undefined,
nodeViewContentRef: () => {
// no-op
},
})
export const useReactNodeView = () => useContext(ReactNodeViewContext)