1.0.1 • Published 2 years ago
@galacsh/keyboard-tree v1.0.1
About
'keyboard-tree' is an tree component for React.
Focused on using keyboard to control the tree.
Visit this demo page to try out.
Installation
npm install @galacsh/keyboard-tree
Guide
Basic
keyboard-tree can only accept this type of data
.
const data = [
// ...
] as KTreeInput[]
interface KTreeInput {
detail: object
children?: KTreeInput[]
}
For the key map, 'key' should be one of KeyboardEvent.code. See below KTreeKeyMap
for available commands which will be mapped to KeyboardEvent.code
.
type KTreeKeyMap = {
[key: string]:
| 'tree/focusOnNodeAbove'
| 'tree/focusOnNodeBelow'
| 'tree/expandNode'
| 'tree/collapseOrFocusOnParentNode'
| 'tree/select'
| 'tree/focusOnFirstNode'
| 'tree/focusOnFirstNode'
| 'tree/focusOnLastNode'
| 'tree/focusOnLastNode',
}
const customKeyMap: KTreeKeyMap = {
ArrowLeft: 'tree/focusOnNodeAbove',
ArrowRight: 'tree/focusOnNodeBelow',
}
Usage Guide
In the examples below, use this.
const exampleData = [
{
detail: {
label: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit,',
},
children: [
{
detail: {
label:
'sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
},
},
{
detail: {
label: 'Blandit turpis cursus in hac',
},
children: [
{
detail: {
label: 'habitasse platea dictumst quisque.',
},
},
],
},
{
detail: {
label:
'Volutpat ac tincidunt vitae semper quis lectus nulla at volutpat.',
},
},
],
},
{
detail: {
label: 'Consequat nisl vel pretium lectus quam id leo.',
},
},
]
Default
// ...
const App = () => (
<KeyboardTree data={exampleData as KTreeInput[]} />
)
Custom key map
// ...
const customKeyMap: KTreeKeyMap = {
ArrowLeft: 'tree/focusOnNodeAbove',
ArrowRight: 'tree/focusOnNodeBelow',
}
const App = () => (
<KeyboardTree
data={exampleData as KTreeInput[]}
keyMap={customKeyMap}
/>
)
Custom node template
// ...
interface Detail extends KTreeNodeData {
detail: { label: string }
}
const CustomNode = ({ data }: { data: Detail }) => {
return (
<div>
<span>{!data.hasChildren ? '- ' : !data.isExpanded ? '> ' : '~ '}</span>
<span style={{ fontWeight: 'bold' }}>[{data.id}]</span>{' '}
{data.detail.label}
</div>
)
}
const App = () => (
<KeyboardTree
data={exampleData as KTreeInput[]}
template={CustomNode}
/>
)
Custom onSelect
function
// ...
function customOnSelect(data: KTreeNodeData) {
// do not alert when selected node has no children
if (!data.hasChildren) {
alert('clicked : ' + data.id)
}
}
const App = () => (
<KeyboardTree
data={exampleData as KTreeInput[]}
onSelect={customOnSelect}
/>
)