1 "use client"
2
3 import * as React from "react"
4
5 import { useDataTableContext } from "@/blocks/data-table/context/use-data-table-context"
6 import { CommandBar } from "@/components/command-bar"
7
8 interface DataTableCommandBarProps {
9 /**
10 * The label to show when items are selected. If a function is passed,
11 * it will be called with the count of selected items.
12 */
13 selectedLabel?: ((count: number) => string) | string
14 }
15
16 /**
17 * This component adds a command bar to the data table, which is used
18 * to show commands that can be executed on the selected rows.
19 */
20 const DataTableCommandBar = (props: DataTableCommandBarProps) => {
21 const { instance } = useDataTableContext()
22
23 const commands = instance.getCommands()
24 const rowSelection = instance.getRowSelection()
25
26 const count = Object.keys(rowSelection || []).length
27
28 const open = commands && commands.length > 0 && count > 0
29
30 function getSelectedLabel(count: number) {
31 if (typeof props.selectedLabel === "function") {
32 return props.selectedLabel(count)
33 }
34
35 return props.selectedLabel
36 }
37
38 if (!commands || commands.length === 0) {
39 return null
40 }
41
42 return (
43 <CommandBar open={open}>
44 <CommandBar.Bar>
45 {props.selectedLabel && (
46 <React.Fragment>
47 <CommandBar.Value>{getSelectedLabel(count)}</CommandBar.Value>
48 <CommandBar.Seperator />
49 </React.Fragment>
50 )}
51 {commands.map((command, idx) => (
52 <React.Fragment key={idx}>
53 <CommandBar.Command
54 key={command.label}
55 action={() => command.action(rowSelection)}
56 label={command.label}
57 shortcut={command.shortcut}
58 />
59 {idx < commands.length - 1 && <CommandBar.Seperator />}
60 </React.Fragment>
61 ))}
62 </CommandBar.Bar>
63 </CommandBar>
64 )
65 }
66 DataTableCommandBar.displayName = "DataTable.CommandBar"
67
68 export { DataTableCommandBar }
69 export type { DataTableCommandBarProps }
70