TableSelector.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. /**
  2. * TableSelector - Header component for switching between sand tables
  3. *
  4. * Displays the current table and provides a dropdown to switch between
  5. * discovered tables or add new ones manually.
  6. */
  7. import { useState } from 'react'
  8. import { useTable, type Table } from '@/contexts/TableContext'
  9. import { Button } from '@/components/ui/button'
  10. import { Input } from '@/components/ui/input'
  11. import { Badge } from '@/components/ui/badge'
  12. import {
  13. Popover,
  14. PopoverContent,
  15. PopoverTrigger,
  16. } from '@/components/ui/popover'
  17. import {
  18. Dialog,
  19. DialogContent,
  20. DialogHeader,
  21. DialogTitle,
  22. DialogFooter,
  23. } from '@/components/ui/dialog'
  24. import { toast } from 'sonner'
  25. import {
  26. Layers,
  27. Plus,
  28. Check,
  29. Pencil,
  30. Trash2,
  31. } from 'lucide-react'
  32. interface TableSelectorProps {
  33. children?: React.ReactNode
  34. }
  35. export function TableSelector({ children }: TableSelectorProps) {
  36. const {
  37. tables,
  38. activeTable,
  39. setActiveTable,
  40. addTable,
  41. removeTable,
  42. updateTableName,
  43. } = useTable()
  44. const [isOpen, setIsOpen] = useState(false)
  45. const [showAddDialog, setShowAddDialog] = useState(false)
  46. const [showRenameDialog, setShowRenameDialog] = useState(false)
  47. const [newTableUrl, setNewTableUrl] = useState('')
  48. const [newTableName, setNewTableName] = useState('')
  49. const [renameTable, setRenameTable] = useState<Table | null>(null)
  50. const [renameValue, setRenameValue] = useState('')
  51. const [isAdding, setIsAdding] = useState(false)
  52. const handleSelectTable = (table: Table) => {
  53. if (table.id !== activeTable?.id) {
  54. setActiveTable(table)
  55. toast.success(`Switched to ${table.name}`)
  56. }
  57. setIsOpen(false)
  58. }
  59. const handleAddTable = async () => {
  60. if (!newTableUrl.trim()) {
  61. toast.error('Please enter a URL')
  62. return
  63. }
  64. setIsAdding(true)
  65. try {
  66. // Ensure URL has protocol
  67. let url = newTableUrl.trim()
  68. if (!url.startsWith('http://') && !url.startsWith('https://')) {
  69. url = `http://${url}`
  70. }
  71. const table = await addTable(url, newTableName.trim() || undefined)
  72. if (table) {
  73. toast.success(`Added ${table.name}`)
  74. setShowAddDialog(false)
  75. setNewTableUrl('')
  76. setNewTableName('')
  77. } else {
  78. toast.error('Failed to add table. Check the URL and try again.')
  79. }
  80. } finally {
  81. setIsAdding(false)
  82. }
  83. }
  84. const handleRename = async () => {
  85. if (!renameTable || !renameValue.trim()) return
  86. await updateTableName(renameTable.id, renameValue.trim())
  87. toast.success('Table renamed')
  88. setShowRenameDialog(false)
  89. setRenameTable(null)
  90. setRenameValue('')
  91. }
  92. const handleRemove = (table: Table) => {
  93. if (table.isCurrent) {
  94. toast.error("Can't remove the current table")
  95. return
  96. }
  97. removeTable(table.id)
  98. toast.success(`Removed ${table.name}`)
  99. }
  100. const openRenameDialog = (table: Table) => {
  101. setRenameTable(table)
  102. setRenameValue(table.name)
  103. setShowRenameDialog(true)
  104. }
  105. // Always show if there are tables or discovering
  106. // This allows users to manually add tables even with just one
  107. return (
  108. <>
  109. <Popover open={isOpen} onOpenChange={setIsOpen}>
  110. <PopoverTrigger asChild>
  111. {children || (
  112. <Button
  113. variant="ghost"
  114. size="sm"
  115. className="gap-2 h-9 px-2"
  116. >
  117. <Layers className="h-4 w-4" />
  118. <span className="hidden sm:inline max-w-[120px] truncate">
  119. {activeTable?.appName || activeTable?.name || 'Select Table'}
  120. </span>
  121. </Button>
  122. )}
  123. </PopoverTrigger>
  124. <PopoverContent className="w-72 p-2" align="start" sideOffset={12} alignOffset={-56}>
  125. <div className="space-y-2">
  126. {/* Header */}
  127. <div className="px-2 py-1">
  128. <span className="text-sm font-medium">Sand Tables</span>
  129. </div>
  130. {/* Table list */}
  131. <div className="space-y-1">
  132. {tables.map(table => (
  133. <div
  134. key={table.id}
  135. className={`flex items-center gap-2 px-2 py-2 rounded-md hover:bg-accent group ${
  136. activeTable?.id === table.id ? 'bg-accent' : ''
  137. }`}
  138. >
  139. <button
  140. type="button"
  141. className="flex-1 flex items-center gap-2 min-w-0 text-left cursor-pointer"
  142. onClick={() => handleSelectTable(table)}
  143. >
  144. {/* Table icon with status indicator */}
  145. <div className="relative flex-shrink-0">
  146. <img
  147. src={
  148. table.customLogo
  149. ? `${table.isCurrent ? '' : table.url}/static/custom/${table.customLogo}`
  150. : `${table.isCurrent ? '' : table.url}/static/android-chrome-192x192.png`
  151. }
  152. alt={table.name}
  153. className="w-8 h-8 rounded-full object-cover"
  154. onError={(e) => {
  155. // Fallback to default icon if image fails to load
  156. (e.target as HTMLImageElement).src = '/static/android-chrome-192x192.png'
  157. }}
  158. />
  159. {/* Online status dot */}
  160. <span
  161. className={`absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full border-2 border-popover ${
  162. table.isOnline ? 'bg-green-500' : 'bg-red-500'
  163. }`}
  164. />
  165. </div>
  166. {/* Name and info */}
  167. <div className="flex-1 min-w-0">
  168. <div className="flex items-center gap-2">
  169. <span className="text-sm truncate">{table.name}</span>
  170. {table.isCurrent && (
  171. <Badge variant="secondary" className="text-[10px] px-1 py-0">
  172. This
  173. </Badge>
  174. )}
  175. </div>
  176. <span className="text-xs text-muted-foreground truncate block">
  177. {table.host || new URL(table.url).hostname}
  178. </span>
  179. </div>
  180. </button>
  181. {/* Actions - always visible on touch, hover-revealed with a fine pointer */}
  182. <div className="flex pointer-fine:opacity-0 pointer-fine:group-hover:opacity-100 pointer-fine:group-focus-within:opacity-100 items-center gap-1 transition-opacity">
  183. <Button
  184. variant="ghost"
  185. size="sm"
  186. className="h-9 w-9 p-0"
  187. onClick={() => openRenameDialog(table)}
  188. title="Rename"
  189. aria-label={`Rename table ${table.name}`}
  190. >
  191. <Pencil className="h-3.5 w-3.5" aria-hidden="true" />
  192. </Button>
  193. {!table.isCurrent && (
  194. <Button
  195. variant="ghost"
  196. size="sm"
  197. className="h-9 w-9 p-0 text-destructive hover:text-destructive"
  198. onClick={() => handleRemove(table)}
  199. title="Remove"
  200. aria-label={`Remove table ${table.name}`}
  201. >
  202. <Trash2 className="h-3.5 w-3.5" aria-hidden="true" />
  203. </Button>
  204. )}
  205. </div>
  206. {/* Selected indicator - far right */}
  207. {activeTable?.id === table.id && (
  208. <Check className="h-4 w-4 text-primary flex-shrink-0" />
  209. )}
  210. </div>
  211. ))}
  212. </div>
  213. {/* Add table button */}
  214. <Button
  215. variant="secondary"
  216. size="sm"
  217. className="w-full gap-2"
  218. onClick={() => setShowAddDialog(true)}
  219. >
  220. <Plus className="h-3.5 w-3.5" />
  221. Add Table Manually
  222. </Button>
  223. </div>
  224. </PopoverContent>
  225. </Popover>
  226. {/* Add Table Dialog */}
  227. <Dialog open={showAddDialog} onOpenChange={setShowAddDialog}>
  228. <DialogContent>
  229. <DialogHeader>
  230. <DialogTitle>Add Table Manually</DialogTitle>
  231. </DialogHeader>
  232. <div className="space-y-4 py-4">
  233. <div className="space-y-2">
  234. <label className="text-sm font-medium">Table URL</label>
  235. <Input
  236. placeholder="192.168.1.100:8080 or http://..."
  237. value={newTableUrl}
  238. onChange={e => setNewTableUrl(e.target.value)}
  239. onKeyDown={e => e.key === 'Enter' && handleAddTable()}
  240. />
  241. <p className="text-xs text-muted-foreground">
  242. Enter the IP address and port of the table's backend
  243. </p>
  244. </div>
  245. <div className="space-y-2">
  246. <label className="text-sm font-medium">Name (optional)</label>
  247. <Input
  248. placeholder="Living Room Table"
  249. value={newTableName}
  250. onChange={e => setNewTableName(e.target.value)}
  251. onKeyDown={e => e.key === 'Enter' && handleAddTable()}
  252. />
  253. </div>
  254. </div>
  255. <DialogFooter className="gap-2 sm:gap-0">
  256. <Button variant="secondary" onClick={() => setShowAddDialog(false)}>
  257. Cancel
  258. </Button>
  259. <Button onClick={handleAddTable} disabled={isAdding}>
  260. {isAdding ? 'Adding...' : 'Add Table'}
  261. </Button>
  262. </DialogFooter>
  263. </DialogContent>
  264. </Dialog>
  265. {/* Rename Dialog */}
  266. <Dialog open={showRenameDialog} onOpenChange={setShowRenameDialog}>
  267. <DialogContent>
  268. <DialogHeader>
  269. <DialogTitle>Rename Table</DialogTitle>
  270. </DialogHeader>
  271. <div className="py-4">
  272. <Input
  273. placeholder="Table name"
  274. value={renameValue}
  275. onChange={e => setRenameValue(e.target.value)}
  276. onKeyDown={e => e.key === 'Enter' && handleRename()}
  277. autoFocus
  278. />
  279. </div>
  280. <DialogFooter className="gap-2 sm:gap-0">
  281. <Button variant="secondary" onClick={() => setShowRenameDialog(false)}>
  282. Cancel
  283. </Button>
  284. <Button onClick={handleRename}>Save</Button>
  285. </DialogFooter>
  286. </DialogContent>
  287. </Dialog>
  288. </>
  289. )
  290. }