Skip to content

Commit

Permalink
refactor: rewrite in typescript
Browse files Browse the repository at this point in the history
  • Loading branch information
simonfan committed Sep 23, 2022
1 parent a0e250c commit d9623ef
Showing 1 changed file with 52 additions and 19 deletions.
71 changes: 52 additions & 19 deletions src/index.jsx → src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,45 @@
import React, { createContext, useContext } from 'react'
import PropTypes from 'prop-types'

export const DEFAULT_TREE_CONTEXT = {
getId: (node) => node.id,
getChildNodes: (node) => node.childNodes,
renderLeaf: ({ id }, { level }) => (
export type Node = {
id: string | number
childNodes?: Node[]
[key: string]: any
}

export type TreeContext = {
getChildNodes: (node: Node) => Node[]
renderBranch: (
node: Node,
opts: {
level: number
index: number
children: React.ReactNode
nodes: Node[]
}
) => JSX.Element
renderLeaf: (
node: Node,
opts: {
level: number
index: number
nodes: Node[]
}
) => JSX.Element
}

export const DEFAULT_TREE_CONTEXT: TreeContext = {
getChildNodes: (node) => node.childNodes || [],
renderLeaf: (node, { level }) => (
<div className='TreeNode TreeNode--Leaf'>
<div className='TreeNode__Label'>
{id} ({level})
{node.id} ({level})
</div>
</div>
),
renderBranch: ({ id }, { children, level }) => (
renderBranch: (node, { children, level }) => (
<div className='TreeNode TreeNode--Branch'>
<div className='TreeNode__Label'>
{id} ({level})
{node.id} ({level})
</div>
<div className='TreeNode__ChildNodeContainer'>{children}</div>
</div>
Expand All @@ -23,14 +48,18 @@ export const DEFAULT_TREE_CONTEXT = {

export const TreeContext = createContext(DEFAULT_TREE_CONTEXT)

export const TreeNodeList = ({ nodes, level = 0 }) => {
const { getId } = useContext(TreeContext)

export const TreeNodeList = ({
nodes,
level = 0,
}: {
nodes: Node[]
level: number
}) => {
return (
<React.Fragment>
{nodes.map((node, index, nodes) => (
<TreeNode
key={getId(node)}
key={node.id}
node={node}
level={level}
index={index}
Expand All @@ -41,11 +70,18 @@ export const TreeNodeList = ({ nodes, level = 0 }) => {
)
}
TreeNodeList.displayName = 'TreeNodeList'
TreeNodeList.propTypes = {
nodes: PropTypes.array.isRequired,
}

export const TreeNode = ({ node, level = 0, index, nodes }) => {
export const TreeNode = ({
node,
level = 0,
index,
nodes,
}: {
node: Node
level?: number
index: number
nodes: Node[]
}) => {
const { getChildNodes, renderLeaf, renderBranch } = useContext(TreeContext)
const childNodes = getChildNodes(node)

Expand All @@ -63,6 +99,3 @@ export const TreeNode = ({ node, level = 0, index, nodes }) => {
})
}
TreeNode.displayName = 'TreeNode'
TreeNode.propTypes = {
node: PropTypes.object.isRequired,
}

0 comments on commit d9623ef

Please sign in to comment.