Last active
February 4, 2022 15:11
-
-
Save rawnly/ff4e4af4e36686172827ecf75cbcaad0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import produce from 'immer'; | |
import { Action, useRegisterActions } from 'kbar'; | |
import { FC, useMemo, useState } from "react"; | |
interface IDemoProps { } | |
const Demo: FC<IDemoProps> = () => { | |
const [counter, setCounter] = useState( 0 ) | |
const [recentActions, setRecentActions] = useState<Record<string, number>>( {} ) | |
const actions: Action[] = [ | |
{ | |
id: 'counter', | |
name: 'Counter', | |
subtitle: 'Manage counter' | |
}, | |
{ | |
id: 'counter.increment', | |
name: 'Increment', | |
subtitle: 'Increments counter value', | |
parent: 'counter', | |
perform: action => { | |
setCounter( c => c + 1 ) | |
setRecentActions( produce( draft => { | |
draft[action.id] = Date.now() | |
} ) ) | |
} | |
}, | |
{ | |
id: 'counter.decrement', | |
name: 'Decrement', | |
subtitle: 'Decrements counter value', | |
parent: 'counter', | |
perform: action => { | |
setCounter( c => c - 1 ) | |
setRecentActions( produce( draft => { | |
draft[action.id] = Date.now() | |
} ) ) | |
} | |
}, | |
] | |
const recents: Action[] = useMemo( () => | |
Object | |
.entries( recentActions ) | |
.sort( ( [_, a], [__, b] ) => b - a ) | |
.map( ( [id] ) => { | |
const originalAction = actions.find( action => action.id === id ) ?? { id, name: id } | |
return { | |
...originalAction, | |
parent: undefined, | |
section: 'Recents' | |
} as Action | |
} ) | |
, [recentActions, actions] ) | |
useRegisterActions( actions ) | |
useRegisterActions( recents, [recents] ) | |
return ( | |
<div> | |
<button onClick={() => setCounter( c => c - 1 )}> | |
Decrement | |
</button> | |
<div>{counter}</div> | |
<button onClick={() => setCounter( c => c + 1 )}> | |
Increment | |
</button> | |
</div> | |
); | |
} | |
export default Demo; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment