VirtualPrinterCard.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. import { useState, useEffect } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import { useMutation, useQueryClient, useQuery } from '@tanstack/react-query';
  4. import {
  5. Loader2, Check, AlertTriangle, Eye, EyeOff, Info,
  6. ChevronDown, ChevronRight, ArrowRightLeft, Trash2,
  7. } from 'lucide-react';
  8. import { api, multiVirtualPrinterApi } from '../api/client';
  9. import type { VirtualPrinterConfig } from '../api/client';
  10. import { Card, CardContent } from './Card';
  11. import { Button } from './Button';
  12. import { ConfirmModal } from './ConfirmModal';
  13. import { useToast } from '../contexts/ToastContext';
  14. type LocalMode = 'immediate' | 'review' | 'print_queue' | 'proxy';
  15. const MODE_LABELS: Record<string, string> = {
  16. immediate: 'archive',
  17. review: 'review',
  18. print_queue: 'queue',
  19. proxy: 'proxy',
  20. };
  21. interface VirtualPrinterCardProps {
  22. printer: VirtualPrinterConfig;
  23. models: Record<string, string>;
  24. }
  25. export function VirtualPrinterCard({ printer, models }: VirtualPrinterCardProps) {
  26. const { t } = useTranslation();
  27. const queryClient = useQueryClient();
  28. const { showToast } = useToast();
  29. const [expanded, setExpanded] = useState(true);
  30. const [localEnabled, setLocalEnabled] = useState(printer.enabled);
  31. const [localName, setLocalName] = useState(printer.name);
  32. const [localAccessCode, setLocalAccessCode] = useState('');
  33. const [localMode, setLocalMode] = useState<LocalMode>(
  34. (printer.mode === 'queue' ? 'review' : printer.mode) as LocalMode
  35. );
  36. const [localTargetPrinterId, setLocalTargetPrinterId] = useState<number | null>(printer.target_printer_id);
  37. const [localBindIp, setLocalBindIp] = useState(printer.bind_ip || '');
  38. const [localRemoteInterfaceIp, setLocalRemoteInterfaceIp] = useState(printer.remote_interface_ip || '');
  39. const [localModel, setLocalModel] = useState(printer.model || '');
  40. const [localAutoDispatch, setLocalAutoDispatch] = useState(printer.auto_dispatch ?? true);
  41. const [showAccessCode, setShowAccessCode] = useState(false);
  42. const [pendingAction, setPendingAction] = useState<string | null>(null);
  43. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  44. // Sync local state when props change (e.g., after backend auto-disable)
  45. useEffect(() => {
  46. if (!pendingAction) {
  47. setLocalEnabled(printer.enabled);
  48. setLocalMode((printer.mode === 'queue' ? 'review' : printer.mode) as LocalMode);
  49. setLocalName(printer.name);
  50. setLocalTargetPrinterId(printer.target_printer_id);
  51. setLocalBindIp(printer.bind_ip || '');
  52. setLocalRemoteInterfaceIp(printer.remote_interface_ip || '');
  53. setLocalModel(printer.model || '');
  54. setLocalAutoDispatch(printer.auto_dispatch ?? true);
  55. }
  56. }, [printer, pendingAction]);
  57. // Fetch printers for dropdown
  58. const { data: printers } = useQuery({
  59. queryKey: ['printers'],
  60. queryFn: api.getPrinters,
  61. });
  62. // Fetch network interfaces
  63. const { data: networkInterfaces } = useQuery({
  64. queryKey: ['network-interfaces'],
  65. queryFn: () => api.getNetworkInterfaces().then(res => res.interfaces),
  66. });
  67. const updateMutation = useMutation({
  68. mutationFn: (data: Parameters<typeof multiVirtualPrinterApi.update>[1]) =>
  69. multiVirtualPrinterApi.update(printer.id, data),
  70. onSuccess: () => {
  71. queryClient.invalidateQueries({ queryKey: ['virtual-printers'] });
  72. showToast(t('virtualPrinter.toast.updated'));
  73. setPendingAction(null);
  74. },
  75. onError: (error: Error) => {
  76. showToast(error.message || t('virtualPrinter.toast.failedToUpdate'), 'error');
  77. setLocalEnabled(printer.enabled);
  78. setLocalMode((printer.mode === 'queue' ? 'review' : printer.mode) as LocalMode);
  79. setLocalTargetPrinterId(printer.target_printer_id);
  80. setLocalBindIp(printer.bind_ip || '');
  81. setPendingAction(null);
  82. },
  83. });
  84. const deleteMutation = useMutation({
  85. mutationFn: () => multiVirtualPrinterApi.remove(printer.id),
  86. onSuccess: () => {
  87. queryClient.invalidateQueries({ queryKey: ['virtual-printers'] });
  88. showToast(t('virtualPrinter.toast.deleted'));
  89. setShowDeleteConfirm(false);
  90. },
  91. onError: (error: Error) => {
  92. showToast(error.message || t('virtualPrinter.toast.failedToDelete'), 'error');
  93. setShowDeleteConfirm(false);
  94. },
  95. });
  96. const handleToggleEnabled = (e: React.MouseEvent) => {
  97. e.stopPropagation();
  98. const newEnabled = !localEnabled;
  99. if (newEnabled) {
  100. if (!localBindIp) {
  101. showToast(t('virtualPrinter.toast.bindIpRequired'), 'error');
  102. return;
  103. }
  104. if (localMode === 'proxy') {
  105. if (!localTargetPrinterId) {
  106. showToast(t('virtualPrinter.toast.targetPrinterRequired'), 'error');
  107. return;
  108. }
  109. } else {
  110. if (!localAccessCode && !printer.access_code_set) {
  111. showToast(t('virtualPrinter.toast.accessCodeRequired'), 'error');
  112. return;
  113. }
  114. }
  115. }
  116. setLocalEnabled(newEnabled);
  117. setPendingAction('toggle');
  118. updateMutation.mutate({ enabled: newEnabled });
  119. };
  120. const handleNameChange = () => {
  121. if (!localName.trim()) return;
  122. setPendingAction('name');
  123. updateMutation.mutate({ name: localName.trim() });
  124. };
  125. const handleAccessCodeChange = () => {
  126. if (!localAccessCode) {
  127. showToast(t('virtualPrinter.toast.accessCodeEmpty'), 'error');
  128. return;
  129. }
  130. if (localAccessCode.length !== 8) {
  131. showToast(t('virtualPrinter.toast.accessCodeLength'), 'error');
  132. return;
  133. }
  134. setPendingAction('accessCode');
  135. updateMutation.mutate({ access_code: localAccessCode });
  136. setLocalAccessCode('');
  137. };
  138. const handleModeChange = (mode: LocalMode) => {
  139. setLocalMode(mode);
  140. setPendingAction('mode');
  141. updateMutation.mutate({ mode });
  142. };
  143. const handleModelChange = (model: string) => {
  144. setLocalModel(model);
  145. setPendingAction('model');
  146. updateMutation.mutate({ model });
  147. };
  148. const handleTargetPrinterChange = (printerId: number) => {
  149. setLocalTargetPrinterId(printerId);
  150. setPendingAction('targetPrinter');
  151. updateMutation.mutate({ target_printer_id: printerId });
  152. };
  153. const handleRemoteInterfaceChange = (ip: string) => {
  154. setLocalRemoteInterfaceIp(ip);
  155. setPendingAction('remoteInterface');
  156. updateMutation.mutate({ remote_interface_ip: ip });
  157. };
  158. const isRunning = printer.status?.running || false;
  159. const modeLabel = t(`virtualPrinter.mode.${MODE_LABELS[localMode] || 'archive'}`);
  160. const targetPrinterName = printers?.find(p => p.id === localTargetPrinterId)?.name;
  161. return (
  162. <>
  163. <Card>
  164. {/* Collapsed header - always visible, clickable to expand */}
  165. <div
  166. className="px-4 py-3 flex items-center gap-3 cursor-pointer select-none"
  167. onClick={() => setExpanded(!expanded)}
  168. >
  169. <button className="text-bambu-gray flex-shrink-0">
  170. {expanded
  171. ? <ChevronDown className="w-4 h-4" />
  172. : <ChevronRight className="w-4 h-4" />
  173. }
  174. </button>
  175. <span className={`w-2 h-2 rounded-full flex-shrink-0 ${isRunning ? 'bg-green-400 animate-pulse' : 'bg-gray-500'}`} />
  176. <span className="text-white font-medium truncate">{printer.name}</span>
  177. <span className="text-xs text-bambu-gray flex-shrink-0">{modeLabel}</span>
  178. {printer.model_name && (
  179. <span className="text-xs text-bambu-gray flex-shrink-0">{printer.model_name}</span>
  180. )}
  181. {targetPrinterName && (
  182. <span className="text-xs text-bambu-gray flex-shrink-0 truncate">
  183. {localMode === 'proxy' && <ArrowRightLeft className="w-3 h-3 inline mr-1" />}
  184. {targetPrinterName}
  185. </span>
  186. )}
  187. {localBindIp && (
  188. <span className="text-[10px] text-bambu-gray flex-shrink-0 font-mono">{localBindIp}</span>
  189. )}
  190. {localRemoteInterfaceIp && (
  191. <span className="text-[10px] text-bambu-gray flex-shrink-0 font-mono">{localRemoteInterfaceIp}</span>
  192. )}
  193. <div className="ml-auto flex items-center gap-2 flex-shrink-0" onClick={(e) => e.stopPropagation()}>
  194. <button
  195. onClick={handleToggleEnabled}
  196. disabled={pendingAction === 'toggle'}
  197. className={`relative w-10 h-5 rounded-full transition-colors ${
  198. localEnabled ? 'bg-bambu-green' : 'bg-bambu-dark-tertiary'
  199. } ${pendingAction === 'toggle' ? 'opacity-50' : ''}`}
  200. >
  201. <span
  202. className={`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${
  203. localEnabled ? 'translate-x-5' : ''
  204. }`}
  205. />
  206. </button>
  207. </div>
  208. </div>
  209. {/* Expanded content */}
  210. {expanded && (
  211. <CardContent className="pt-0 space-y-4">
  212. <div className="border-t border-bambu-dark-tertiary" />
  213. {/* Name + delete */}
  214. <div className="flex items-center gap-2">
  215. <input
  216. type="text"
  217. value={localName}
  218. onChange={(e) => setLocalName(e.target.value)}
  219. onBlur={handleNameChange}
  220. onKeyDown={(e) => e.key === 'Enter' && handleNameChange()}
  221. className="flex-1 text-sm text-white bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 focus:border-bambu-green focus:outline-none"
  222. />
  223. <span className="text-xs text-bambu-gray font-mono">{printer.serial}</span>
  224. <button
  225. onClick={() => setShowDeleteConfirm(true)}
  226. className="p-1.5 text-bambu-gray hover:text-red-400 transition-colors"
  227. title={t('common.delete')}
  228. >
  229. <Trash2 className="w-4 h-4" />
  230. </button>
  231. </div>
  232. {/* Mode */}
  233. <div>
  234. <div className="text-white text-sm font-medium mb-2">{t('virtualPrinter.mode.title')}</div>
  235. <div className="grid grid-cols-2 gap-2">
  236. {(['immediate', 'review', 'print_queue', 'proxy'] as const).map((mode) => (
  237. <button
  238. key={mode}
  239. onClick={() => handleModeChange(mode)}
  240. disabled={pendingAction === 'mode'}
  241. className={`p-2 rounded-lg border text-left transition-colors ${
  242. localMode === mode
  243. ? mode === 'proxy'
  244. ? 'border-blue-500 bg-blue-500/10'
  245. : 'border-bambu-green bg-bambu-green/10'
  246. : 'border-bambu-dark-tertiary hover:border-bambu-gray'
  247. }`}
  248. >
  249. <div className="flex items-center gap-1.5 text-white text-xs font-medium">
  250. {mode === 'proxy' && <ArrowRightLeft className="w-3 h-3" />}
  251. {t(`virtualPrinter.mode.${MODE_LABELS[mode]}`)}
  252. </div>
  253. <div className="text-[10px] text-bambu-gray">
  254. {t(`virtualPrinter.mode.${MODE_LABELS[mode]}Desc`)}
  255. </div>
  256. </button>
  257. ))}
  258. </div>
  259. </div>
  260. {/* Auto-dispatch toggle - only for print_queue mode */}
  261. {localMode === 'print_queue' && (
  262. <div className="pt-2 border-t border-bambu-dark-tertiary">
  263. <div className="flex items-center justify-between">
  264. <div>
  265. <div className="text-white text-sm font-medium">{t('virtualPrinter.autoDispatch.title')}</div>
  266. <div className="text-[10px] text-bambu-gray">{t('virtualPrinter.autoDispatch.description')}</div>
  267. </div>
  268. <button
  269. onClick={() => {
  270. const newVal = !localAutoDispatch;
  271. setLocalAutoDispatch(newVal);
  272. setPendingAction('autoDispatch');
  273. updateMutation.mutate({ auto_dispatch: newVal });
  274. }}
  275. disabled={pendingAction === 'autoDispatch'}
  276. className={`relative w-10 h-5 rounded-full transition-colors flex-shrink-0 ${
  277. localAutoDispatch ? 'bg-bambu-green' : 'bg-bambu-dark-tertiary'
  278. } ${pendingAction === 'autoDispatch' ? 'opacity-50' : ''}`}
  279. >
  280. <span
  281. className={`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${
  282. localAutoDispatch ? 'translate-x-5' : ''
  283. }`}
  284. />
  285. </button>
  286. </div>
  287. </div>
  288. )}
  289. {/* Printer Model - for non-proxy modes */}
  290. {localMode !== 'proxy' && (
  291. <div className="pt-2 border-t border-bambu-dark-tertiary">
  292. <div className="text-white text-sm font-medium mb-1">{t('virtualPrinter.model.title')}</div>
  293. <p className="text-xs text-bambu-gray mb-2">{t('virtualPrinter.model.description')}</p>
  294. <div className="relative">
  295. <select
  296. value={localModel}
  297. onChange={(e) => handleModelChange(e.target.value)}
  298. disabled={pendingAction === 'model'}
  299. className="w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-white text-sm appearance-none cursor-pointer disabled:opacity-50 pr-10"
  300. >
  301. {Object.entries(models).map(([code, name]) => (
  302. <option key={code} value={code}>{name} ({code})</option>
  303. ))}
  304. </select>
  305. <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none" />
  306. </div>
  307. </div>
  308. )}
  309. {/* Proxy mode: hint about using target printer's access code */}
  310. {localMode === 'proxy' && (
  311. <div className="pt-2 border-t border-bambu-dark-tertiary">
  312. <div className="flex items-start gap-2 p-2 rounded bg-blue-500/10 border border-blue-500/30">
  313. <Info className="w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5" />
  314. <p className="text-xs text-bambu-gray">
  315. {t('virtualPrinter.proxy.accessCodeHint')}
  316. </p>
  317. </div>
  318. </div>
  319. )}
  320. {/* Access Code - only for non-proxy modes */}
  321. {localMode !== 'proxy' && (
  322. <div className="pt-2 border-t border-bambu-dark-tertiary">
  323. <div className="flex items-center gap-2 mb-2">
  324. <div className="text-white text-sm font-medium">{t('virtualPrinter.accessCode.title')}</div>
  325. {printer.access_code_set ? (
  326. <span className="flex items-center gap-1 text-xs text-green-400">
  327. <Check className="w-3 h-3" />
  328. {t('virtualPrinter.accessCode.isSet')}
  329. </span>
  330. ) : (
  331. <span className="flex items-center gap-1 text-xs text-yellow-400">
  332. <AlertTriangle className="w-3 h-3" />
  333. {t('virtualPrinter.accessCode.notSet')}
  334. </span>
  335. )}
  336. </div>
  337. <div className="flex gap-2">
  338. <div className="relative flex-1">
  339. <input
  340. type={showAccessCode ? 'text' : 'password'}
  341. value={localAccessCode}
  342. onChange={(e) => setLocalAccessCode(e.target.value)}
  343. placeholder={printer.access_code_set ? t('virtualPrinter.accessCode.placeholderChange') : t('virtualPrinter.accessCode.placeholder')}
  344. maxLength={8}
  345. className="w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-white text-sm placeholder-bambu-gray pr-10 font-mono"
  346. />
  347. <button
  348. onClick={() => setShowAccessCode(!showAccessCode)}
  349. className="absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white"
  350. >
  351. {showAccessCode ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
  352. </button>
  353. </div>
  354. <Button
  355. onClick={handleAccessCodeChange}
  356. disabled={!localAccessCode || pendingAction === 'accessCode'}
  357. variant="primary"
  358. >
  359. {pendingAction === 'accessCode' ? <Loader2 className="w-4 h-4 animate-spin" /> : t('common.save')}
  360. </Button>
  361. </div>
  362. {localAccessCode && (
  363. <p className="text-xs text-bambu-gray mt-1">
  364. <span className={localAccessCode.length === 8 ? 'text-green-400' : 'text-yellow-400'}>
  365. {t('virtualPrinter.accessCode.charCount', { count: localAccessCode.length })}
  366. </span>
  367. </p>
  368. )}
  369. </div>
  370. )}
  371. {/* Target Printer */}
  372. <div className="pt-2 border-t border-bambu-dark-tertiary">
  373. <div className="text-white text-sm font-medium mb-2">{t('virtualPrinter.targetPrinter.title')}</div>
  374. <div className="relative">
  375. <select
  376. value={localTargetPrinterId ?? ''}
  377. onChange={(e) => {
  378. const id = parseInt(e.target.value, 10);
  379. if (!isNaN(id)) handleTargetPrinterChange(id);
  380. }}
  381. disabled={pendingAction === 'targetPrinter'}
  382. className="w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-white text-sm appearance-none cursor-pointer disabled:opacity-50 pr-10"
  383. >
  384. <option value="">{t('virtualPrinter.targetPrinter.placeholder')}</option>
  385. {printers?.map((p) => (
  386. <option key={p.id} value={p.id}>{p.name} ({p.ip_address})</option>
  387. ))}
  388. </select>
  389. <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none" />
  390. </div>
  391. </div>
  392. {/* Bind Interface */}
  393. <div className="pt-2 border-t border-bambu-dark-tertiary">
  394. <div className="text-white text-sm font-medium mb-1">{t('virtualPrinter.bindIp.title')}</div>
  395. <div className="relative">
  396. <select
  397. value={localBindIp}
  398. onChange={(e) => {
  399. setLocalBindIp(e.target.value);
  400. setPendingAction('bindIp');
  401. updateMutation.mutate({ bind_ip: e.target.value });
  402. }}
  403. disabled={pendingAction === 'bindIp'}
  404. className="w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-white text-sm appearance-none cursor-pointer disabled:opacity-50 pr-10"
  405. >
  406. <option value="">{t('virtualPrinter.bindIp.placeholder')}</option>
  407. {networkInterfaces?.map((iface) => (
  408. <option key={iface.ip} value={iface.ip}>
  409. {iface.name} ({iface.ip}){iface.is_alias ? ' [alias]' : ''} - {iface.subnet}
  410. </option>
  411. ))}
  412. </select>
  413. <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none" />
  414. </div>
  415. <p className="text-xs text-bambu-gray mt-1">{t('virtualPrinter.bindIp.hint')}</p>
  416. </div>
  417. {/* Remote Interface - always visible for configuration */}
  418. <div className="pt-2 border-t border-bambu-dark-tertiary">
  419. <div className="flex items-center gap-2 mb-1">
  420. <div className="text-white text-sm font-medium">{t('virtualPrinter.remoteInterface.title')}</div>
  421. {localRemoteInterfaceIp ? (
  422. <span className="flex items-center gap-1 text-xs text-green-400"><Check className="w-3 h-3" /></span>
  423. ) : (
  424. <span className="flex items-center gap-1 text-xs text-bambu-gray" title={t('virtualPrinter.remoteInterface.optional')}><Info className="w-3 h-3" /></span>
  425. )}
  426. </div>
  427. <div className="relative">
  428. <select
  429. value={localRemoteInterfaceIp}
  430. onChange={(e) => handleRemoteInterfaceChange(e.target.value)}
  431. disabled={pendingAction === 'remoteInterface'}
  432. className="w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-white text-sm appearance-none cursor-pointer disabled:opacity-50 pr-10"
  433. >
  434. <option value="">{t('virtualPrinter.remoteInterface.placeholder')}</option>
  435. {networkInterfaces?.map((iface) => (
  436. <option key={iface.ip} value={iface.ip}>
  437. {iface.name} ({iface.ip}) - {iface.subnet}
  438. </option>
  439. ))}
  440. </select>
  441. <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none" />
  442. </div>
  443. </div>
  444. </CardContent>
  445. )}
  446. </Card>
  447. {showDeleteConfirm && (
  448. <ConfirmModal
  449. title={t('virtualPrinter.deleteConfirm.title')}
  450. message={t('virtualPrinter.deleteConfirm.message', { name: printer.name })}
  451. variant="danger"
  452. confirmText={t('common.delete')}
  453. isLoading={deleteMutation.isPending}
  454. onConfirm={() => deleteMutation.mutate()}
  455. onCancel={() => setShowDeleteConfirm(false)}
  456. />
  457. )}
  458. </>
  459. );
  460. }