SmartPlugCard.tsx 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. import { useState } from 'react';
  2. import { useMutation, useQueryClient, useQuery } from '@tanstack/react-query';
  3. import { Plug, Power, PowerOff, Loader2, Trash2, Settings2, Thermometer, Clock, Wifi, WifiOff, Edit2, Bell, Calendar, LayoutGrid, ExternalLink, Home, Radio, Eye, Globe } from 'lucide-react';
  4. import { useTranslation } from 'react-i18next';
  5. import { api } from '../api/client';
  6. import type { SmartPlug, SmartPlugTempSource, SmartPlugUpdate } from '../api/client';
  7. import { Card, CardContent } from './Card';
  8. import { Button } from './Button';
  9. import { ConfirmModal } from './ConfirmModal';
  10. import { useToast } from '../contexts/ToastContext';
  11. import { NumberInput } from './NumberInput';
  12. // What temperature-based auto-off can wait for (#3464), in display order.
  13. const TEMP_SOURCES: { value: SmartPlugTempSource; labelKey: string; descriptionKey: string }[] = [
  14. { value: 'nozzle', labelKey: 'smartPlugs.tempSourceNozzle', descriptionKey: 'smartPlugs.tempSourceNozzleDescription' },
  15. { value: 'bed', labelKey: 'smartPlugs.tempSourceBed', descriptionKey: 'smartPlugs.tempSourceBedDescription' },
  16. ];
  17. interface SmartPlugCardProps {
  18. plug: SmartPlug;
  19. onEdit: (plug: SmartPlug) => void;
  20. }
  21. export function SmartPlugCard({ plug, onEdit }: SmartPlugCardProps) {
  22. const { t } = useTranslation();
  23. const queryClient = useQueryClient();
  24. const { showToast } = useToast();
  25. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  26. const [showPowerOnConfirm, setShowPowerOnConfirm] = useState(false);
  27. const [showPowerOffConfirm, setShowPowerOffConfirm] = useState(false);
  28. const [isExpanded, setIsExpanded] = useState(false);
  29. // Fetch current status
  30. const { data: status, isLoading: statusLoading } = useQuery({
  31. queryKey: ['smart-plug-status', plug.id],
  32. queryFn: () => api.getSmartPlugStatus(plug.id),
  33. refetchInterval: 30000, // Refresh every 30 seconds
  34. });
  35. // Fetch printers for linking
  36. const { data: printers } = useQuery({
  37. queryKey: ['printers'],
  38. queryFn: api.getPrinters,
  39. });
  40. const linkedPrinter = printers?.find(p => p.id === plug.printer_id);
  41. // Anything unknown waits for the nozzle, as the backend does.
  42. const tempSource = TEMP_SOURCES.find((s) => s.value === plug.off_temp_source) ?? TEMP_SOURCES[0];
  43. // Control mutation with optimistic updates
  44. const controlMutation = useMutation({
  45. mutationFn: (action: 'on' | 'off' | 'toggle') => api.controlSmartPlug(plug.id, action),
  46. onMutate: async (action) => {
  47. // Cancel any outgoing refetches
  48. await queryClient.cancelQueries({ queryKey: ['smart-plug-status', plug.id] });
  49. // Snapshot the previous value
  50. const previousStatus = queryClient.getQueryData(['smart-plug-status', plug.id]);
  51. // Optimistically update to the new value
  52. const newState = action === 'on' ? 'ON' : action === 'off' ? 'OFF' : (status?.state === 'ON' ? 'OFF' : 'ON');
  53. queryClient.setQueryData(['smart-plug-status', plug.id], (old: typeof status) => ({
  54. ...old,
  55. state: newState,
  56. }));
  57. return { previousStatus };
  58. },
  59. onError: (_err, action, context) => {
  60. // Rollback on error
  61. if (context?.previousStatus) {
  62. queryClient.setQueryData(['smart-plug-status', plug.id], context.previousStatus);
  63. }
  64. showToast(t('smartPlugs.failedToTurn', { action, name: plug.name }), 'error');
  65. },
  66. onSettled: () => {
  67. // Refetch after a short delay to get actual state
  68. setTimeout(() => {
  69. queryClient.invalidateQueries({ queryKey: ['smart-plug-status', plug.id] });
  70. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  71. }, 1000);
  72. },
  73. });
  74. // Update mutation
  75. const updateMutation = useMutation({
  76. mutationFn: (data: SmartPlugUpdate) => api.updateSmartPlug(plug.id, data),
  77. onSuccess: () => {
  78. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  79. // Also invalidate printer-specific smart plug queries to keep PrintersPage in sync
  80. if (plug.printer_id) {
  81. queryClient.invalidateQueries({ queryKey: ['smartPlugByPrinter', plug.printer_id] });
  82. queryClient.invalidateQueries({ queryKey: ['scriptPlugsByPrinter', plug.printer_id] });
  83. }
  84. },
  85. });
  86. // Delete mutation
  87. const deleteMutation = useMutation({
  88. mutationFn: () => api.deleteSmartPlug(plug.id),
  89. onSuccess: () => {
  90. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  91. // Also invalidate printer card HA entity queries
  92. if (plug.printer_id) {
  93. queryClient.invalidateQueries({ queryKey: ['scriptPlugsByPrinter', plug.printer_id] });
  94. }
  95. },
  96. });
  97. const isOn = status?.state === 'ON';
  98. // For MQTT plugs, consider reachable if we have power data (even if backend says not reachable)
  99. const hasMqttData = plug.plug_type === 'mqtt' && (status?.energy?.power !== null && status?.energy?.power !== undefined);
  100. const isReachable = (status?.reachable ?? false) || hasMqttData;
  101. const isPending = controlMutation.isPending;
  102. // Generate admin URL with auto-login credentials (Tasmota only)
  103. const getAdminUrl = () => {
  104. if (plug.plug_type !== 'tasmota' || !plug.ip_address) return null;
  105. const ip = plug.ip_address;
  106. if (plug.username && plug.password) {
  107. // Use HTTP Basic Auth in URL for auto-login
  108. return `http://${encodeURIComponent(plug.username)}:${encodeURIComponent(plug.password)}@${ip}/`;
  109. }
  110. return `http://${ip}/`;
  111. };
  112. const adminUrl = getAdminUrl();
  113. return (
  114. <>
  115. <Card className="relative">
  116. <CardContent className="p-4">
  117. {/* Header Row */}
  118. <div className="flex items-start justify-between gap-2 mb-3">
  119. <div className="flex items-center gap-3 min-w-0 flex-1">
  120. <div className={`p-2 rounded-lg flex-shrink-0 ${
  121. plug.plug_type === 'mqtt'
  122. ? (isReachable ? 'bg-teal-100 dark:bg-teal-500/20' : 'bg-red-100 dark:bg-red-500/20')
  123. : (isReachable ? (isOn ? 'bg-bambu-green/20' : 'bg-bambu-dark') : 'bg-red-100 dark:bg-red-500/20')
  124. }`}>
  125. {plug.plug_type === 'mqtt' ? (
  126. <Radio className={`w-5 h-5 ${isReachable ? 'text-teal-600 dark:text-teal-400' : 'text-red-600 dark:text-red-400'}`} />
  127. ) : plug.plug_type === 'homeassistant' ? (
  128. <Home className={`w-5 h-5 ${isReachable ? (isOn ? 'text-bambu-green' : 'text-bambu-gray') : 'text-red-600 dark:text-red-400'}`} />
  129. ) : plug.plug_type === 'rest' ? (
  130. <Globe className={`w-5 h-5 ${isReachable ? (isOn ? 'text-bambu-green' : 'text-bambu-gray') : 'text-red-600 dark:text-red-400'}`} />
  131. ) : (
  132. <Plug className={`w-5 h-5 ${isReachable ? (isOn ? 'text-bambu-green' : 'text-bambu-gray') : 'text-red-600 dark:text-red-400'}`} />
  133. )}
  134. </div>
  135. <div className="min-w-0">
  136. <h3 className="font-medium text-white truncate">{plug.name}</h3>
  137. <p
  138. className="text-sm text-bambu-gray truncate"
  139. title={plug.plug_type === 'mqtt' ? plug.mqtt_topic ?? undefined : plug.plug_type === 'homeassistant' ? plug.ha_entity_id ?? undefined : plug.plug_type === 'rest' ? plug.rest_on_url || plug.rest_off_url || 'REST' : plug.ip_address ?? undefined}
  140. >
  141. {plug.plug_type === 'mqtt' ? plug.mqtt_topic : plug.plug_type === 'homeassistant' ? plug.ha_entity_id : plug.plug_type === 'rest' ? (plug.rest_on_url || plug.rest_off_url || 'REST') : plug.ip_address}
  142. </p>
  143. </div>
  144. </div>
  145. {/* Status indicator */}
  146. <div className="flex flex-col items-end gap-1 flex-shrink-0">
  147. {statusLoading ? (
  148. <Loader2 className="w-4 h-4 text-bambu-gray animate-spin" />
  149. ) : plug.plug_type === 'mqtt' ? (
  150. /* MQTT plugs - show badge and checkmark when receiving data */
  151. <div className="flex items-center gap-1.5 text-sm whitespace-nowrap">
  152. <span className="px-1.5 py-0.5 bg-teal-100 dark:bg-teal-500/20 text-teal-700 dark:text-teal-400 text-[10px] font-medium rounded flex-shrink-0">MQTT</span>
  153. {isReachable && <span className="text-status-ok">✓</span>}
  154. </div>
  155. ) : plug.plug_type === 'homeassistant' ? (
  156. <div className="flex items-center gap-1 text-sm">
  157. <span className="px-1 py-0.5 bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 text-[10px] font-medium rounded">HA</span>
  158. <span className={isReachable ? (isOn ? 'text-status-ok' : 'text-bambu-gray') : 'text-status-error'}>
  159. {isReachable ? (status?.state || '?') : t('smartPlugs.offline')}
  160. </span>
  161. </div>
  162. ) : plug.plug_type === 'rest' ? (
  163. <div className="flex items-center gap-1 text-sm">
  164. <span className="px-1 py-0.5 bg-purple-100 dark:bg-purple-500/20 text-purple-700 dark:text-purple-400 text-[10px] font-medium rounded">REST</span>
  165. <span className={isReachable ? (isOn ? 'text-status-ok' : 'text-bambu-gray') : 'text-status-error'}>
  166. {isReachable ? (status?.state || '?') : t('smartPlugs.offline')}
  167. </span>
  168. </div>
  169. ) : isReachable ? (
  170. <div className="flex items-center gap-1 text-sm">
  171. <Wifi className="w-4 h-4 text-status-ok" />
  172. <span className={isOn ? 'text-status-ok' : 'text-bambu-gray'}>{status?.state || t('smartPlugs.unknown')}</span>
  173. </div>
  174. ) : (
  175. <div className="flex items-center gap-1 text-sm text-status-error">
  176. <WifiOff className="w-4 h-4" />
  177. <span>{t('smartPlugs.offline')}</span>
  178. </div>
  179. )}
  180. {/* Admin page link - only for Tasmota */}
  181. {adminUrl && (
  182. <a
  183. href={adminUrl}
  184. target="_blank"
  185. rel="noopener noreferrer"
  186. className="flex items-center gap-1 px-2 py-0.5 bg-bambu-dark hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white text-xs rounded-full transition-colors"
  187. title={t('smartPlugs.openPlugAdminPage')}
  188. >
  189. <ExternalLink className="w-3 h-3" />
  190. {t('smartPlugs.admin')}
  191. </a>
  192. )}
  193. </div>
  194. </div>
  195. {/* Linked Printer */}
  196. {linkedPrinter && (
  197. <div className="mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg">
  198. <span className="text-xs text-bambu-gray">{t('smartPlugs.linkedTo')} </span>
  199. <span className="text-sm text-white">{linkedPrinter.name}</span>
  200. </div>
  201. )}
  202. {/* Feature Badges */}
  203. {(plug.power_alert_enabled || plug.schedule_enabled || plug.plug_type === 'mqtt') && (
  204. <div className="flex flex-wrap gap-1.5 mb-3">
  205. {plug.plug_type === 'mqtt' && (
  206. <span className="flex items-center gap-1 px-2 py-0.5 bg-teal-100 dark:bg-teal-500/20 text-teal-700 dark:text-teal-400 text-xs rounded-full">
  207. <Eye className="w-3 h-3" />
  208. {t('smartPlugs.monitorOnly')}
  209. </span>
  210. )}
  211. {plug.power_alert_enabled && (
  212. <span className="flex items-center gap-1 px-2 py-0.5 bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400 text-xs rounded-full">
  213. <Bell className="w-3 h-3" />
  214. {t('smartPlugs.alerts')}
  215. </span>
  216. )}
  217. {plug.schedule_enabled && (
  218. <span className="flex items-center gap-1 px-2 py-0.5 bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 text-xs rounded-full">
  219. <Calendar className="w-3 h-3" />
  220. {plug.schedule_on_time && plug.schedule_off_time
  221. ? `${plug.schedule_on_time} - ${plug.schedule_off_time}`
  222. : plug.schedule_on_time
  223. ? t('smartPlugs.scheduleOn', { time: plug.schedule_on_time })
  224. : t('smartPlugs.scheduleOff', { time: plug.schedule_off_time })}
  225. </span>
  226. )}
  227. </div>
  228. )}
  229. {/* Quick Controls - hidden for MQTT plugs (monitor-only) */}
  230. {plug.plug_type !== 'mqtt' && (
  231. <div className="flex gap-2 mb-3">
  232. <Button
  233. size="sm"
  234. variant={isOn ? 'primary' : 'secondary'}
  235. disabled={!isReachable || isPending}
  236. onClick={() => setShowPowerOnConfirm(true)}
  237. className="flex-1"
  238. >
  239. {isPending ? <Loader2 className="w-4 h-4 animate-spin" /> : <Power className="w-4 h-4" />}
  240. {t('smartPlugs.on')}
  241. </Button>
  242. <Button
  243. size="sm"
  244. variant={!isOn ? 'primary' : 'secondary'}
  245. disabled={!isReachable || isPending}
  246. onClick={() => setShowPowerOffConfirm(true)}
  247. className="flex-1"
  248. >
  249. {isPending ? <Loader2 className="w-4 h-4 animate-spin" /> : <PowerOff className="w-4 h-4" />}
  250. {t('smartPlugs.off')}
  251. </Button>
  252. </div>
  253. )}
  254. {/* Energy display for MQTT plugs */}
  255. {plug.plug_type === 'mqtt' && status?.energy && (
  256. <div className="flex gap-2 mb-3 px-3 py-2 bg-bambu-dark rounded-lg">
  257. {status.energy.power !== null && status.energy.power !== undefined && (
  258. <div className="flex-1 text-center">
  259. <p className="text-lg font-semibold text-white">{Math.round(status.energy.power)}W</p>
  260. <p className="text-xs text-bambu-gray">{t('smartPlugs.power')}</p>
  261. </div>
  262. )}
  263. {status.energy.today !== null && status.energy.today !== undefined && (
  264. <div className="flex-1 text-center border-l border-bambu-dark-tertiary">
  265. <p className="text-lg font-semibold text-white">{status.energy.today.toFixed(3)}</p>
  266. <p className="text-xs text-bambu-gray">{t('smartPlugs.kwhToday')}</p>
  267. </div>
  268. )}
  269. </div>
  270. )}
  271. {/* Toggle Settings Panel */}
  272. <button
  273. onClick={() => setIsExpanded(!isExpanded)}
  274. className="w-full flex items-center justify-between py-2 text-sm text-bambu-gray hover:text-white transition-colors"
  275. >
  276. <span className="flex items-center gap-2">
  277. <Settings2 className="w-4 h-4" />
  278. {plug.plug_type === 'mqtt' ? t('smartPlugs.settings') : t('smartPlugs.automationSettings')}
  279. </span>
  280. <span>{isExpanded ? '-' : '+'}</span>
  281. </button>
  282. {/* Expanded Settings */}
  283. {isExpanded && (
  284. <div className="pt-3 border-t border-bambu-dark-tertiary space-y-4">
  285. {/* Show in Switchbar Toggle */}
  286. <div className="flex items-center justify-between">
  287. <div className="flex items-center gap-2">
  288. <LayoutGrid className="w-4 h-4 text-bambu-green" />
  289. <div>
  290. <p className="text-sm text-white">{t('smartPlugs.showInSwitchbar')}</p>
  291. <p className="text-xs text-bambu-gray">{t('smartPlugs.quickAccessSidebar')}</p>
  292. </div>
  293. </div>
  294. <label className="relative inline-flex items-center cursor-pointer">
  295. <input
  296. type="checkbox"
  297. checked={plug.show_in_switchbar}
  298. onChange={(e) => updateMutation.mutate({ show_in_switchbar: e.target.checked })}
  299. className="sr-only peer"
  300. />
  301. <div className="w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"></div>
  302. </label>
  303. </div>
  304. {/* Powers the printer (#2629) - only meaningful with a linked printer.
  305. When off, switching this plug off no longer marks the printer offline. */}
  306. {plug.printer_id != null && (
  307. <div className="flex items-center justify-between">
  308. <div className="flex items-center gap-2">
  309. <Power className="w-4 h-4 text-bambu-green" />
  310. <div>
  311. <p className="text-sm text-white">{t('smartPlugs.controlsPrinterPower')}</p>
  312. <p className="text-xs text-bambu-gray">{t('smartPlugs.controlsPrinterPowerDescription')}</p>
  313. </div>
  314. </div>
  315. <label className="relative inline-flex items-center cursor-pointer">
  316. <input
  317. type="checkbox"
  318. checked={plug.controls_printer_power}
  319. onChange={(e) => updateMutation.mutate({ controls_printer_power: e.target.checked })}
  320. className="sr-only peer"
  321. />
  322. <div className="w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"></div>
  323. </label>
  324. </div>
  325. )}
  326. {/* Automation controls - only for controllable plugs (not MQTT) */}
  327. {plug.plug_type !== 'mqtt' && (
  328. <>
  329. {/* Enabled Toggle */}
  330. <div className="flex items-center justify-between">
  331. <div>
  332. <p className="text-sm text-white">{t('smartPlugs.enabled')}</p>
  333. <p className="text-xs text-bambu-gray">{t('smartPlugs.enableAutomation')}</p>
  334. </div>
  335. <label className="relative inline-flex items-center cursor-pointer">
  336. <input
  337. type="checkbox"
  338. checked={plug.enabled}
  339. onChange={(e) => updateMutation.mutate({ enabled: e.target.checked })}
  340. className="sr-only peer"
  341. />
  342. <div className="w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"></div>
  343. </label>
  344. </div>
  345. {/* Auto On */}
  346. <div className="flex items-center justify-between">
  347. <div>
  348. <p className="text-sm text-white">{t('smartPlugs.autoOn')}</p>
  349. <p className="text-xs text-bambu-gray">{t('smartPlugs.autoOnDescription')}</p>
  350. </div>
  351. <label className="relative inline-flex items-center cursor-pointer">
  352. <input
  353. type="checkbox"
  354. checked={plug.auto_on}
  355. onChange={(e) => updateMutation.mutate({ auto_on: e.target.checked })}
  356. className="sr-only peer"
  357. />
  358. <div className="w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"></div>
  359. </label>
  360. </div>
  361. {/* Auto Off */}
  362. <div className="flex items-center justify-between">
  363. <div>
  364. <p className="text-sm text-white">{t('smartPlugs.autoOff')}</p>
  365. <p className="text-xs text-bambu-gray">{t('smartPlugs.autoOffDescription')}</p>
  366. </div>
  367. <label className="relative inline-flex items-center cursor-pointer">
  368. <input
  369. type="checkbox"
  370. checked={plug.auto_off}
  371. onChange={(e) => updateMutation.mutate({ auto_off: e.target.checked })}
  372. className="sr-only peer"
  373. />
  374. <div className="w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"></div>
  375. </label>
  376. </div>
  377. {/* Auto Off Persistent */}
  378. {plug.auto_off && (
  379. <div className="flex items-center justify-between pl-4 border-l-2 border-bambu-dark-tertiary">
  380. <div>
  381. <p className="text-sm text-white">{t('smartPlugs.autoOffPersistent')}</p>
  382. <p className="text-xs text-bambu-gray">{t('smartPlugs.autoOffPersistentDescription')}</p>
  383. </div>
  384. <label className="relative inline-flex items-center cursor-pointer">
  385. <input
  386. type="checkbox"
  387. checked={plug.auto_off_persistent}
  388. onChange={(e) => updateMutation.mutate({ auto_off_persistent: e.target.checked })}
  389. className="sr-only peer"
  390. />
  391. <div className="w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"></div>
  392. </label>
  393. </div>
  394. )}
  395. {/* Delay Mode */}
  396. {plug.auto_off && (
  397. <div className="space-y-3 pl-4 border-l-2 border-bambu-dark-tertiary">
  398. <div>
  399. <p className="text-sm text-white mb-2">{t('smartPlugs.turnOffDelayMode')}</p>
  400. <div className="flex gap-2">
  401. <button
  402. onClick={() => updateMutation.mutate({ off_delay_mode: 'time' })}
  403. className={`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${
  404. plug.off_delay_mode === 'time'
  405. ? 'bg-bambu-green text-white'
  406. : 'bg-bambu-dark text-bambu-gray hover:text-white'
  407. }`}
  408. >
  409. <Clock className="w-4 h-4" />
  410. {t('smartPlugs.time')}
  411. </button>
  412. <button
  413. onClick={() => updateMutation.mutate({ off_delay_mode: 'temperature' })}
  414. className={`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${
  415. plug.off_delay_mode === 'temperature'
  416. ? 'bg-bambu-green text-white'
  417. : 'bg-bambu-dark text-bambu-gray hover:text-white'
  418. }`}
  419. >
  420. <Thermometer className="w-4 h-4" />
  421. {t('smartPlugs.temp')}
  422. </button>
  423. </div>
  424. </div>
  425. {plug.off_delay_mode === 'time' ? (
  426. <div>
  427. <label className="block text-xs text-bambu-gray mb-1">{t('smartPlugs.delayMinutes')}</label>
  428. <NumberInput
  429. min={1}
  430. max={60}
  431. value={plug.off_delay_minutes}
  432. onChange={(v) => updateMutation.mutate({ off_delay_minutes: v })}
  433. fallback={5}
  434. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none"
  435. />
  436. </div>
  437. ) : (
  438. <>
  439. {/* What has to cool before the plug turns off (#3464):
  440. the bed stays hot long after the nozzle. */}
  441. <div>
  442. <p className="text-xs text-bambu-gray mb-1">{t('smartPlugs.tempSource')}</p>
  443. <div className="flex gap-2">
  444. {TEMP_SOURCES.map(({ value, labelKey }) => (
  445. <button
  446. key={value}
  447. onClick={() => updateMutation.mutate({ off_temp_source: value })}
  448. className={`flex-1 px-3 py-1.5 rounded-lg text-sm transition-colors ${
  449. tempSource.value === value
  450. ? 'bg-bambu-green text-white'
  451. : 'bg-bambu-dark text-bambu-gray hover:text-white'
  452. }`}
  453. >
  454. {t(labelKey)}
  455. </button>
  456. ))}
  457. </div>
  458. <p className="text-xs text-bambu-gray mt-1">
  459. {t(tempSource.descriptionKey)}
  460. </p>
  461. </div>
  462. {tempSource.value === 'nozzle' && (
  463. <div>
  464. <label className="block text-xs text-bambu-gray mb-1">{t('smartPlugs.nozzleTempThreshold')}</label>
  465. <NumberInput
  466. min={30}
  467. max={100}
  468. value={plug.off_temp_threshold}
  469. onChange={(v) => updateMutation.mutate({ off_temp_threshold: v })}
  470. fallback={70}
  471. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none"
  472. />
  473. </div>
  474. )}
  475. {tempSource.value === 'bed' && (
  476. <div>
  477. <label className="block text-xs text-bambu-gray mb-1">{t('smartPlugs.bedTempThreshold')}</label>
  478. <NumberInput
  479. min={20}
  480. max={100}
  481. value={plug.off_bed_temp_threshold}
  482. onChange={(v) => updateMutation.mutate({ off_bed_temp_threshold: v })}
  483. fallback={35}
  484. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none"
  485. />
  486. <p className="text-xs text-bambu-gray mt-1">{t('smartPlugs.bedTempThresholdDescription')}</p>
  487. </div>
  488. )}
  489. </>
  490. )}
  491. </div>
  492. )}
  493. {/* Auto Off After Drying (#1349) — independent of the
  494. print-finish auto-off above. Uses its own delay because
  495. the AMS chamber is hot post-cycle and users often want
  496. more cooldown than the print-finish default. Fires when
  497. any AMS attached to the linked printer finishes a dry
  498. cycle. */}
  499. <div className="flex items-center justify-between">
  500. <div>
  501. <p className="text-sm text-white">{t('smartPlugs.autoOffAfterDrying')}</p>
  502. <p className="text-xs text-bambu-gray">{t('smartPlugs.autoOffAfterDryingDescription')}</p>
  503. </div>
  504. <label className="relative inline-flex items-center cursor-pointer">
  505. <input
  506. type="checkbox"
  507. checked={plug.auto_off_after_drying}
  508. onChange={(e) => updateMutation.mutate({ auto_off_after_drying: e.target.checked })}
  509. className="sr-only peer"
  510. />
  511. <div className="w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"></div>
  512. </label>
  513. </div>
  514. {plug.auto_off_after_drying && (
  515. <div className="pl-4 border-l-2 border-bambu-dark-tertiary">
  516. <label className="block text-xs text-bambu-gray mb-1">{t('smartPlugs.delayAfterDryingMinutes')}</label>
  517. <NumberInput
  518. min={0}
  519. max={120}
  520. value={plug.off_delay_after_drying_minutes}
  521. onChange={(v) => updateMutation.mutate({ off_delay_after_drying_minutes: v })}
  522. fallback={10}
  523. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none"
  524. />
  525. </div>
  526. )}
  527. </>
  528. )}
  529. {/* Action Buttons */}
  530. <div className="flex gap-2 pt-2">
  531. <Button
  532. size="sm"
  533. variant="secondary"
  534. onClick={() => onEdit(plug)}
  535. className="flex-1"
  536. >
  537. <Edit2 className="w-4 h-4" />
  538. {t('smartPlugs.edit')}
  539. </Button>
  540. <Button
  541. size="sm"
  542. variant="secondary"
  543. onClick={() => setShowDeleteConfirm(true)}
  544. className="text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300"
  545. >
  546. <Trash2 className="w-4 h-4" />
  547. </Button>
  548. </div>
  549. </div>
  550. )}
  551. </CardContent>
  552. </Card>
  553. {/* Delete Confirmation */}
  554. {showDeleteConfirm && (
  555. <ConfirmModal
  556. title={t('smartPlugs.deleteSmartPlug')}
  557. message={t('smartPlugs.deleteConfirm', { name: plug.name })}
  558. confirmText={t('smartPlugs.delete')}
  559. variant="danger"
  560. onConfirm={() => {
  561. deleteMutation.mutate();
  562. setShowDeleteConfirm(false);
  563. }}
  564. onCancel={() => setShowDeleteConfirm(false)}
  565. />
  566. )}
  567. {/* Power On Confirmation */}
  568. {showPowerOnConfirm && (
  569. <ConfirmModal
  570. title={t('smartPlugs.turnOnSmartPlug')}
  571. message={t('smartPlugs.turnOnConfirm', { name: plug.name })}
  572. confirmText={t('smartPlugs.turnOn')}
  573. variant="default"
  574. onConfirm={() => {
  575. controlMutation.mutate('on');
  576. setShowPowerOnConfirm(false);
  577. }}
  578. onCancel={() => setShowPowerOnConfirm(false)}
  579. />
  580. )}
  581. {/* Power Off Confirmation */}
  582. {showPowerOffConfirm && (
  583. <ConfirmModal
  584. title={t('smartPlugs.turnOffSmartPlug')}
  585. message={t('smartPlugs.turnOffConfirm', { name: plug.name })}
  586. confirmText={t('smartPlugs.turnOff')}
  587. variant="danger"
  588. onConfirm={() => {
  589. controlMutation.mutate('off');
  590. setShowPowerOffConfirm(false);
  591. }}
  592. onCancel={() => setShowPowerOffConfirm(false)}
  593. />
  594. )}
  595. </>
  596. );
  597. }