-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTabs.tsx
108 lines (95 loc) · 2.9 KB
/
Tabs.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import { IconPlus } from "@tabler/icons-react"
import clsx from "clsx"
import { FC, useEffect, useRef, useState } from "react"
import { useGetTabsList, useMutateTabs } from "../store"
import { useOnClickOutside } from "../utils/useOnClickOutside"
type TabDto = ReturnType<typeof useGetTabsList>[0]
const Tab: FC<{ tab: TabDto; canDelete: boolean }> = ({ tab, canDelete }) => {
const { delTab, setActive, setName } = useMutateTabs()
const [edit, setEdit] = useState(false)
const [input, setInput] = useState("")
const click = () => {
if (!tab.isActive) {
setActive(tab.id)
} else {
setEdit(true)
setInput("") // todo: select current text
}
}
const apply = () => {
if (!edit) return
if (input.trim().length) setName(tab.id, input.trim())
setEdit(false)
}
const ref = useRef<HTMLInputElement>(null)
useOnClickOutside(ref, apply)
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (e.key === "Enter") apply()
}
window.addEventListener("keydown", handler)
return () => window.removeEventListener("keydown", handler)
}, [input])
return (
<div
onClick={() => click()}
className={clsx(
"flex h-[32px] select-none items-center justify-between gap-1.5 border-t-2 border-transparent",
canDelete ? "pl-4 pr-1" : "px-4",
!tab.isActive && "cursor-pointer",
tab.isActive && "border-blue-500 bg-body/50",
)}
>
<div className="min-w-[48px] grow">
{edit ? (
<input
ref={ref}
autoFocus
value={input}
onChange={(e) => setInput(e.target.value)}
className="max-w-[100px] bg-card text-body-content outline-none"
/>
) : (
<div className={clsx(tab.isActive && "cursor-text")}>{tab.name}</div>
)}
</div>
{canDelete && (
<button
onClick={() => delTab(tab.id)}
disabled={!canDelete}
className={clsx(
"flex h-[17px] w-[17px] items-center justify-center rounded-full font-mono text-[15px]",
"text-card-content/50 hover:bg-gray-500/30 hover:text-red-500",
"transition-colors",
)}
>
×
</button>
)}
</div>
)
}
export const Tabs: FC = () => {
const tabs = useGetTabsList()
const { addTab } = useMutateTabs()
return (
<div className="flex items-center rounded-lg text-sm leading-none">
<div className="flex flex-wrap">
{tabs.map((x) => (
<Tab key={x.id} tab={x} canDelete={tabs.length > 1} />
))}
</div>
<button
key="add"
aria-label="add tab"
onClick={addTab}
className={clsx(
"mx-1 flex h-6 w-6 items-center justify-center rounded-full hover:bg-gray-200",
"transition-colors",
)}
>
<IconPlus className="h-5 w-5" />
</button>
</div>
)
}