VirtualPrinterCard.tsx 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  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, ShieldCheck, Copy, Stethoscope,
  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 { VirtualPrinterDiagnosticModal } from './VirtualPrinterDiagnosticModal';
  14. import { useToast } from '../contexts/ToastContext';
  15. import { copyTextToClipboard } from '../utils/clipboard';
  16. type LocalMode = 'archive' | 'review' | 'queue' | 'proxy';
  17. const MODE_LABELS: Record<string, string> = {
  18. archive: 'archive',
  19. review: 'review',
  20. queue: 'queue',
  21. proxy: 'proxy',
  22. };
  23. // Legacy wire values (`immediate` → `archive`, `print_queue` → `queue`) shipped
  24. // before the UI labels were aligned with the wire format. Backend migration
  25. // flips existing rows but the function tolerates either form so a stale fetch
  26. // doesn't show an unselected mode (#1429 follow-up).
  27. function normalizeMode(value: string | undefined): LocalMode {
  28. if (value === 'immediate') return 'archive';
  29. if (value === 'print_queue' || value === 'queue') return 'queue';
  30. if (value === 'archive' || value === 'review' || value === 'proxy') return value;
  31. return 'archive';
  32. }
  33. interface VirtualPrinterCardProps {
  34. printer: VirtualPrinterConfig;
  35. models: Record<string, string>;
  36. }
  37. export function VirtualPrinterCard({ printer, models }: VirtualPrinterCardProps) {
  38. const { t } = useTranslation();
  39. const queryClient = useQueryClient();
  40. const { showToast } = useToast();
  41. const [expanded, setExpanded] = useState(true);
  42. const [localEnabled, setLocalEnabled] = useState(printer.enabled);
  43. const [localName, setLocalName] = useState(printer.name);
  44. const [localAccessCode, setLocalAccessCode] = useState('');
  45. const [localMode, setLocalMode] = useState<LocalMode>(normalizeMode(printer.mode));
  46. const [localTargetPrinterId, setLocalTargetPrinterId] = useState<number | null>(printer.target_printer_id);
  47. const [localBindIp, setLocalBindIp] = useState(printer.bind_ip || '');
  48. const [localRemoteInterfaceIp, setLocalRemoteInterfaceIp] = useState(printer.remote_interface_ip || '');
  49. const [localModel, setLocalModel] = useState(printer.model || '');
  50. const [localAutoDispatch, setLocalAutoDispatch] = useState(printer.auto_dispatch ?? true);
  51. const [localQueueForceColorMatch, setLocalQueueForceColorMatch] = useState(printer.queue_force_color_match ?? false);
  52. const [localSaveAmsMapping, setLocalSaveAmsMapping] = useState(printer.save_ams_mapping ?? false);
  53. const [localGcodeInjection, setLocalGcodeInjection] = useState(printer.gcode_injection ?? false);
  54. const [localTailscaleDisabled, setLocalTailscaleDisabled] = useState(printer.tailscale_disabled ?? true);
  55. const [showAccessCode, setShowAccessCode] = useState(false);
  56. const [pendingAction, setPendingAction] = useState<string | null>(null);
  57. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  58. const [showDiagnostic, setShowDiagnostic] = useState(false);
  59. const [fqdnCopied, setFqdnCopied] = useState(false);
  60. // Host-level Tailscale identity (same for every VP) — shown inline on the card when
  61. // the user has marked this VP as "exposed over Tailscale". Cert handling does NOT
  62. // depend on this toggle; the slicer trusts the bambuddy CA the user imports once.
  63. const { data: tailscaleStatus } = useQuery({
  64. queryKey: ['tailscale-status'],
  65. queryFn: multiVirtualPrinterApi.getTailscaleStatus,
  66. enabled: !localTailscaleDisabled,
  67. staleTime: 60_000,
  68. });
  69. const tailscaleFqdn = tailscaleStatus?.available ? tailscaleStatus.fqdn : '';
  70. const tailscaleIp = tailscaleStatus?.available ? tailscaleStatus.tailscale_ips?.[0] ?? '' : '';
  71. const handleCopyFqdn = async (e: React.MouseEvent) => {
  72. e.stopPropagation();
  73. const fqdn = tailscaleFqdn;
  74. if (!fqdn) return;
  75. const ok = await copyTextToClipboard(fqdn);
  76. if (ok) {
  77. setFqdnCopied(true);
  78. showToast(t('printers.copied'));
  79. setTimeout(() => setFqdnCopied(false), 2000);
  80. } else {
  81. showToast(t('virtualPrinter.toast.copyFailed'), 'error');
  82. }
  83. };
  84. // Sync local state when props change (e.g., after backend auto-disable)
  85. useEffect(() => {
  86. if (!pendingAction) {
  87. setLocalEnabled(printer.enabled);
  88. setLocalMode(normalizeMode(printer.mode));
  89. setLocalName(printer.name);
  90. setLocalTargetPrinterId(printer.target_printer_id);
  91. setLocalBindIp(printer.bind_ip || '');
  92. setLocalRemoteInterfaceIp(printer.remote_interface_ip || '');
  93. setLocalModel(printer.model || '');
  94. setLocalAutoDispatch(printer.auto_dispatch ?? true);
  95. setLocalQueueForceColorMatch(printer.queue_force_color_match ?? false);
  96. setLocalSaveAmsMapping(printer.save_ams_mapping ?? false);
  97. setLocalGcodeInjection(printer.gcode_injection ?? false);
  98. setLocalTailscaleDisabled(printer.tailscale_disabled ?? true);
  99. }
  100. }, [printer, pendingAction]);
  101. // Fetch printers for dropdown
  102. const { data: printers } = useQuery({
  103. queryKey: ['printers'],
  104. queryFn: api.getPrinters,
  105. });
  106. // Fetch network interfaces
  107. const { data: networkInterfaces } = useQuery({
  108. queryKey: ['network-interfaces'],
  109. queryFn: () => api.getNetworkInterfaces().then(res => res.interfaces),
  110. });
  111. const updateMutation = useMutation({
  112. mutationFn: (data: Parameters<typeof multiVirtualPrinterApi.update>[1]) =>
  113. multiVirtualPrinterApi.update(printer.id, data),
  114. onSuccess: () => {
  115. queryClient.invalidateQueries({ queryKey: ['virtual-printers'] });
  116. showToast(t('virtualPrinter.toast.updated'));
  117. setPendingAction(null);
  118. },
  119. onError: (error: Error) => {
  120. showToast(error.message || t('virtualPrinter.toast.failedToUpdate'), 'error');
  121. setLocalEnabled(printer.enabled);
  122. setLocalMode(normalizeMode(printer.mode));
  123. setLocalTargetPrinterId(printer.target_printer_id);
  124. setLocalBindIp(printer.bind_ip || '');
  125. setLocalTailscaleDisabled(printer.tailscale_disabled ?? true);
  126. // Queue-mode behaviour toggles. Without these the switch stays visually
  127. // flipped after a failed save, so the card claims a setting the server
  128. // never accepted.
  129. setLocalQueueForceColorMatch(printer.queue_force_color_match ?? false);
  130. setLocalSaveAmsMapping(printer.save_ams_mapping ?? false);
  131. setLocalGcodeInjection(printer.gcode_injection ?? false);
  132. setPendingAction(null);
  133. },
  134. });
  135. const deleteMutation = useMutation({
  136. mutationFn: () => multiVirtualPrinterApi.remove(printer.id),
  137. onSuccess: () => {
  138. queryClient.invalidateQueries({ queryKey: ['virtual-printers'] });
  139. showToast(t('virtualPrinter.toast.deleted'));
  140. setShowDeleteConfirm(false);
  141. },
  142. onError: (error: Error) => {
  143. showToast(error.message || t('virtualPrinter.toast.failedToDelete'), 'error');
  144. setShowDeleteConfirm(false);
  145. },
  146. });
  147. const handleToggleEnabled = (e: React.MouseEvent) => {
  148. e.stopPropagation();
  149. const newEnabled = !localEnabled;
  150. if (newEnabled) {
  151. if (!localBindIp) {
  152. showToast(t('virtualPrinter.toast.bindIpRequired'), 'error');
  153. return;
  154. }
  155. if (localMode === 'proxy') {
  156. if (!localTargetPrinterId) {
  157. showToast(t('virtualPrinter.toast.targetPrinterRequired'), 'error');
  158. return;
  159. }
  160. } else {
  161. if (!localAccessCode && !printer.access_code_set) {
  162. showToast(t('virtualPrinter.toast.accessCodeRequired'), 'error');
  163. return;
  164. }
  165. }
  166. }
  167. setLocalEnabled(newEnabled);
  168. setPendingAction('toggle');
  169. updateMutation.mutate({ enabled: newEnabled });
  170. };
  171. const handleNameChange = () => {
  172. if (!localName.trim()) return;
  173. setPendingAction('name');
  174. updateMutation.mutate({ name: localName.trim() });
  175. };
  176. const handleAccessCodeChange = () => {
  177. if (!localAccessCode) {
  178. showToast(t('virtualPrinter.toast.accessCodeEmpty'), 'error');
  179. return;
  180. }
  181. if (localAccessCode.length !== 8) {
  182. showToast(t('virtualPrinter.toast.accessCodeLength'), 'error');
  183. return;
  184. }
  185. setPendingAction('accessCode');
  186. updateMutation.mutate({ access_code: localAccessCode });
  187. setLocalAccessCode('');
  188. };
  189. const handleModeChange = (mode: LocalMode) => {
  190. setLocalMode(mode);
  191. setPendingAction('mode');
  192. updateMutation.mutate({ mode });
  193. };
  194. const handleModelChange = (model: string) => {
  195. setLocalModel(model);
  196. setPendingAction('model');
  197. updateMutation.mutate({ model });
  198. };
  199. const handleTargetPrinterChange = (printerId: number) => {
  200. // The new target's access code becomes this VP's access code on the
  201. // backend write. If the slicer was already bound with the old code,
  202. // it has to rebind; flag this so the user doesn't sit there confused.
  203. const previousCode = targetPrinter?.access_code;
  204. const nextCode = printers?.find(p => p.id === printerId)?.access_code;
  205. setLocalTargetPrinterId(printerId);
  206. setPendingAction('targetPrinter');
  207. updateMutation.mutate(
  208. { target_printer_id: printerId },
  209. {
  210. onSuccess: () => {
  211. if (previousCode && nextCode && previousCode !== nextCode) {
  212. showToast(t('virtualPrinter.toast.targetCodeChangedRebind'), 'info');
  213. }
  214. },
  215. },
  216. );
  217. };
  218. const handleRemoteInterfaceChange = (ip: string) => {
  219. setLocalRemoteInterfaceIp(ip);
  220. setPendingAction('remoteInterface');
  221. updateMutation.mutate({ remote_interface_ip: ip });
  222. };
  223. const isRunning = printer.status?.running || false;
  224. const modeLabel = t(`virtualPrinter.mode.${MODE_LABELS[localMode] || 'archive'}`);
  225. const targetPrinter = printers?.find(p => p.id === localTargetPrinterId);
  226. const targetPrinterName = targetPrinter?.name;
  227. // The bridge in non-proxy modes (and the transparent relay in proxy mode)
  228. // forwards the slicer's auth bytes to the real printer, so the VP's access
  229. // code is always the target's. When a target is set, the card surfaces the
  230. // target's code read-only — the user types it into the slicer, but can't
  231. // diverge it from the printer.
  232. const inheritsAccessCodeFromTarget = !!localTargetPrinterId;
  233. const inheritedAccessCode = inheritsAccessCodeFromTarget ? (targetPrinter?.access_code ?? '') : '';
  234. return (
  235. <>
  236. <Card>
  237. {/* Collapsed header - always visible, clickable to expand */}
  238. <div
  239. className="px-4 py-3 flex items-center gap-3 cursor-pointer select-none"
  240. onClick={() => setExpanded(!expanded)}
  241. >
  242. <button className="text-bambu-gray flex-shrink-0">
  243. {expanded
  244. ? <ChevronDown className="w-4 h-4" />
  245. : <ChevronRight className="w-4 h-4" />
  246. }
  247. </button>
  248. <span className={`w-2 h-2 rounded-full flex-shrink-0 ${isRunning ? 'bg-green-400 animate-pulse' : 'bg-gray-500'}`} />
  249. <span className="text-white font-medium truncate">{printer.name}</span>
  250. <span className="text-xs text-bambu-gray flex-shrink-0">{modeLabel}</span>
  251. {printer.model_name && (
  252. <span className="text-xs text-bambu-gray flex-shrink-0">{printer.model_name}</span>
  253. )}
  254. {targetPrinterName && (
  255. <span className="text-xs text-bambu-gray flex-shrink-0 truncate">
  256. {localMode === 'proxy' && <ArrowRightLeft className="w-3 h-3 inline mr-1" />}
  257. {targetPrinterName}
  258. </span>
  259. )}
  260. {localBindIp && (
  261. <span className="text-[10px] text-bambu-gray flex-shrink-0 font-mono">{localBindIp}</span>
  262. )}
  263. {localRemoteInterfaceIp && (
  264. <span className="text-[10px] text-bambu-gray flex-shrink-0 font-mono">{localRemoteInterfaceIp}</span>
  265. )}
  266. <div className="ml-auto flex items-center gap-2 flex-shrink-0" onClick={(e) => e.stopPropagation()}>
  267. <button
  268. onClick={handleToggleEnabled}
  269. disabled={pendingAction === 'toggle'}
  270. className={`relative w-10 h-5 rounded-full transition-colors ${
  271. localEnabled ? 'bg-bambu-green' : 'bg-bambu-dark-tertiary'
  272. } ${pendingAction === 'toggle' ? 'opacity-50' : ''}`}
  273. >
  274. <span
  275. className={`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${
  276. localEnabled ? 'translate-x-5' : ''
  277. }`}
  278. />
  279. </button>
  280. </div>
  281. </div>
  282. {/* Expanded content */}
  283. {expanded && (
  284. <CardContent className="pt-0 space-y-4">
  285. <div className="border-t border-bambu-dark-tertiary" />
  286. {/* Name + delete */}
  287. <div className="flex items-center gap-2">
  288. <input
  289. type="text"
  290. value={localName}
  291. onChange={(e) => setLocalName(e.target.value)}
  292. onBlur={handleNameChange}
  293. onKeyDown={(e) => e.key === 'Enter' && handleNameChange()}
  294. 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"
  295. />
  296. <button
  297. onClick={() => setShowDiagnostic(true)}
  298. className="p-1.5 text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0"
  299. title={t('vpDiagnostic.runButton')}
  300. >
  301. <Stethoscope className="w-4 h-4" />
  302. </button>
  303. <button
  304. onClick={() => setShowDeleteConfirm(true)}
  305. className="p-1.5 text-bambu-gray hover:text-red-600 dark:hover:text-red-400 transition-colors flex-shrink-0"
  306. title={t('common.delete')}
  307. >
  308. <Trash2 className="w-4 h-4" />
  309. </button>
  310. </div>
  311. {/* Tailscale identity (host-level) + serial — compact info row.
  312. Shown only when this VP is marked Tailscale-exposed AND the daemon is up. */}
  313. <div className="flex items-center gap-2 -mt-2">
  314. {tailscaleFqdn && (
  315. <span className="flex items-center gap-1 text-green-700/80 dark:text-green-400/70 min-w-0">
  316. <ShieldCheck className="w-3.5 h-3.5 flex-shrink-0" />
  317. <span className="font-mono text-xs truncate">
  318. {tailscaleIp ? `${tailscaleIp} (${tailscaleFqdn})` : tailscaleFqdn}
  319. </span>
  320. <button
  321. onClick={handleCopyFqdn}
  322. className="p-0.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors flex-shrink-0"
  323. title={fqdnCopied ? t('printers.copied') : t('printers.copyToClipboard')}
  324. >
  325. {fqdnCopied ? (
  326. <Check className="w-3.5 h-3.5 text-bambu-green" />
  327. ) : (
  328. <Copy className="w-3.5 h-3.5" />
  329. )}
  330. </button>
  331. </span>
  332. )}
  333. <span className="text-xs text-bambu-gray font-mono ml-auto flex-shrink-0">{printer.serial}</span>
  334. </div>
  335. {/* Mode */}
  336. <div>
  337. <div className="text-white text-sm font-medium mb-2">{t('virtualPrinter.mode.title')}</div>
  338. <div className="grid grid-cols-2 gap-2">
  339. {(['archive', 'review', 'queue', 'proxy'] as const).map((mode) => (
  340. <button
  341. key={mode}
  342. onClick={() => handleModeChange(mode)}
  343. disabled={pendingAction === 'mode'}
  344. className={`p-2 rounded-lg border text-left transition-colors ${
  345. localMode === mode
  346. ? mode === 'proxy'
  347. ? 'border-blue-500 bg-blue-500/10'
  348. : 'border-bambu-green bg-bambu-green/10'
  349. : 'border-bambu-dark-tertiary hover:border-bambu-gray'
  350. }`}
  351. >
  352. <div className="flex items-center gap-1.5 text-white text-xs font-medium">
  353. {mode === 'proxy' && <ArrowRightLeft className="w-3 h-3" />}
  354. {t(`virtualPrinter.mode.${MODE_LABELS[mode]}`)}
  355. </div>
  356. <div className="text-[10px] text-bambu-gray">
  357. {t(`virtualPrinter.mode.${MODE_LABELS[mode]}Desc`)}
  358. </div>
  359. </button>
  360. ))}
  361. </div>
  362. </div>
  363. {/* Auto-dispatch toggle - only for queue mode */}
  364. {localMode === 'queue' && (
  365. <div className="pt-2 border-t border-bambu-dark-tertiary">
  366. <div className="flex items-center justify-between gap-3">
  367. <div className="min-w-0">
  368. <div className="text-white text-sm font-medium">{t('virtualPrinter.autoDispatch.title')}</div>
  369. <div className="text-[10px] text-bambu-gray">{t('virtualPrinter.autoDispatch.description')}</div>
  370. </div>
  371. <button
  372. onClick={() => {
  373. const newVal = !localAutoDispatch;
  374. setLocalAutoDispatch(newVal);
  375. setPendingAction('autoDispatch');
  376. updateMutation.mutate({ auto_dispatch: newVal });
  377. }}
  378. disabled={pendingAction === 'autoDispatch'}
  379. className={`relative w-10 h-5 rounded-full transition-colors flex-shrink-0 ${
  380. localAutoDispatch ? 'bg-bambu-green' : 'bg-bambu-dark-tertiary'
  381. } ${pendingAction === 'autoDispatch' ? 'opacity-50' : ''}`}
  382. >
  383. <span
  384. className={`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${
  385. localAutoDispatch ? 'translate-x-5' : ''
  386. }`}
  387. />
  388. </button>
  389. </div>
  390. </div>
  391. )}
  392. {/* Force-color-match toggle - only for queue mode (#1188) */}
  393. {localMode === 'queue' && (
  394. <div className="pt-2 border-t border-bambu-dark-tertiary">
  395. <div className="flex items-center justify-between gap-3">
  396. <div className="min-w-0">
  397. <div className="text-white text-sm font-medium">{t('virtualPrinter.queueForceColorMatch.title')}</div>
  398. <div className="text-[10px] text-bambu-gray">{t('virtualPrinter.queueForceColorMatch.description')}</div>
  399. </div>
  400. <button
  401. onClick={() => {
  402. const newVal = !localQueueForceColorMatch;
  403. setLocalQueueForceColorMatch(newVal);
  404. setPendingAction('queueForceColorMatch');
  405. updateMutation.mutate({ queue_force_color_match: newVal });
  406. }}
  407. disabled={pendingAction === 'queueForceColorMatch'}
  408. className={`relative w-10 h-5 rounded-full transition-colors flex-shrink-0 ${
  409. localQueueForceColorMatch ? 'bg-bambu-green' : 'bg-bambu-dark-tertiary'
  410. } ${pendingAction === 'queueForceColorMatch' ? 'opacity-50' : ''}`}
  411. >
  412. <span
  413. className={`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${
  414. localQueueForceColorMatch ? 'translate-x-5' : ''
  415. }`}
  416. />
  417. </button>
  418. </div>
  419. </div>
  420. )}
  421. {/* Save-AMS-mapping toggle - only for queue mode */}
  422. {localMode === 'queue' && (
  423. <div className="pt-2 border-t border-bambu-dark-tertiary">
  424. <div className="flex items-center justify-between gap-3">
  425. <div className="min-w-0">
  426. <div className="text-white text-sm font-medium">{t('virtualPrinter.saveAmsMapping.title')}</div>
  427. <div className="text-[10px] text-bambu-gray">{t('virtualPrinter.saveAmsMapping.description')}</div>
  428. </div>
  429. <button
  430. onClick={() => {
  431. const newVal = !localSaveAmsMapping;
  432. setLocalSaveAmsMapping(newVal);
  433. setPendingAction('saveAmsMapping');
  434. updateMutation.mutate({ save_ams_mapping: newVal });
  435. }}
  436. disabled={pendingAction === 'saveAmsMapping'}
  437. className={`relative w-10 h-5 rounded-full transition-colors flex-shrink-0 ${
  438. localSaveAmsMapping ? 'bg-bambu-green' : 'bg-bambu-dark-tertiary'
  439. } ${pendingAction === 'saveAmsMapping' ? 'opacity-50' : ''}`}
  440. >
  441. <span
  442. className={`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${
  443. localSaveAmsMapping ? 'translate-x-5' : ''
  444. }`}
  445. />
  446. </button>
  447. </div>
  448. </div>
  449. )}
  450. {/* G-code injection toggle - only for queue mode (#1516) */}
  451. {localMode === 'queue' && (
  452. <div className="pt-2 border-t border-bambu-dark-tertiary">
  453. <div className="flex items-center justify-between gap-3">
  454. <div className="min-w-0">
  455. <div className="text-white text-sm font-medium">{t('virtualPrinter.gcodeInjection.title')}</div>
  456. <div className="text-[10px] text-bambu-gray">{t('virtualPrinter.gcodeInjection.description')}</div>
  457. </div>
  458. <button
  459. onClick={() => {
  460. const newVal = !localGcodeInjection;
  461. setLocalGcodeInjection(newVal);
  462. setPendingAction('gcodeInjection');
  463. updateMutation.mutate({ gcode_injection: newVal });
  464. }}
  465. disabled={pendingAction === 'gcodeInjection'}
  466. className={`relative w-10 h-5 rounded-full transition-colors flex-shrink-0 ${
  467. localGcodeInjection ? 'bg-bambu-green' : 'bg-bambu-dark-tertiary'
  468. } ${pendingAction === 'gcodeInjection' ? 'opacity-50' : ''}`}
  469. >
  470. <span
  471. className={`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${
  472. localGcodeInjection ? 'translate-x-5' : ''
  473. }`}
  474. />
  475. </button>
  476. </div>
  477. </div>
  478. )}
  479. {/* Tailscale toggle */}
  480. <div className="pt-2 border-t border-bambu-dark-tertiary">
  481. <div className="flex items-center justify-between gap-3">
  482. <div className="min-w-0">
  483. <div className="text-white text-sm font-medium">{t('virtualPrinter.tailscaleDisabled.title')}</div>
  484. <div className="text-[10px] text-bambu-gray">{t('virtualPrinter.tailscaleDisabled.description')}</div>
  485. </div>
  486. <button
  487. onClick={() => {
  488. const newVal = !localTailscaleDisabled;
  489. setLocalTailscaleDisabled(newVal);
  490. setPendingAction('tailscaleDisabled');
  491. updateMutation.mutate({ tailscale_disabled: newVal });
  492. }}
  493. disabled={pendingAction === 'tailscaleDisabled'}
  494. className={`relative w-10 h-5 rounded-full transition-colors shrink-0 ${
  495. !localTailscaleDisabled ? 'bg-bambu-green' : 'bg-bambu-dark-tertiary'
  496. } ${pendingAction === 'tailscaleDisabled' ? 'opacity-50' : ''}`}
  497. >
  498. <span
  499. className={`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${
  500. !localTailscaleDisabled ? 'translate-x-5' : ''
  501. }`}
  502. />
  503. </button>
  504. </div>
  505. </div>
  506. {/* Printer Model - for non-proxy modes */}
  507. {localMode !== 'proxy' && (
  508. <div className="pt-2 border-t border-bambu-dark-tertiary">
  509. <div className="text-white text-sm font-medium mb-1">{t('virtualPrinter.model.title')}</div>
  510. <p className="text-xs text-bambu-gray mb-2">{t('virtualPrinter.model.description')}</p>
  511. <div className="relative">
  512. <select
  513. value={localModel}
  514. onChange={(e) => handleModelChange(e.target.value)}
  515. disabled={pendingAction === 'model'}
  516. 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"
  517. >
  518. {Object.entries(models).map(([code, name]) => (
  519. <option key={code} value={code}>{name} ({code})</option>
  520. ))}
  521. </select>
  522. <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none" />
  523. </div>
  524. </div>
  525. )}
  526. {/* Proxy mode: hint about using target printer's access code */}
  527. {localMode === 'proxy' && (
  528. <div className="pt-2 border-t border-bambu-dark-tertiary">
  529. <div className="flex items-start gap-2 p-2 rounded bg-blue-50 border border-blue-300 dark:bg-blue-500/10 dark:border-blue-500/30">
  530. <Info className="w-4 h-4 text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5" />
  531. <p className="text-xs text-bambu-gray">
  532. {t('virtualPrinter.proxy.accessCodeHint')}
  533. </p>
  534. </div>
  535. </div>
  536. )}
  537. {/* Access Code - only for non-proxy modes */}
  538. {localMode !== 'proxy' && (
  539. <div className="pt-2 border-t border-bambu-dark-tertiary">
  540. <div className="flex items-center gap-2 mb-2">
  541. <div className="text-white text-sm font-medium">{t('virtualPrinter.accessCode.title')}</div>
  542. {inheritsAccessCodeFromTarget ? (
  543. <span className="flex items-center gap-1 text-xs text-blue-700 dark:text-blue-400">
  544. <Info className="w-3 h-3" />
  545. {t('virtualPrinter.accessCode.inheritedFromTarget')}
  546. </span>
  547. ) : printer.access_code_set ? (
  548. <span className="flex items-center gap-1 text-xs text-green-700 dark:text-green-400">
  549. <Check className="w-3 h-3" />
  550. {t('virtualPrinter.accessCode.isSet')}
  551. </span>
  552. ) : (
  553. <span className="flex items-center gap-1 text-xs text-yellow-700 dark:text-yellow-400">
  554. <AlertTriangle className="w-3 h-3" />
  555. {t('virtualPrinter.accessCode.notSet')}
  556. </span>
  557. )}
  558. </div>
  559. {inheritsAccessCodeFromTarget ? (
  560. <>
  561. <div className="relative">
  562. <input
  563. type={showAccessCode ? 'text' : 'password'}
  564. value={inheritedAccessCode}
  565. readOnly
  566. aria-label={t('virtualPrinter.accessCode.title')}
  567. className="w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-white text-sm pr-10 font-mono opacity-90 cursor-default"
  568. />
  569. <button
  570. onClick={() => setShowAccessCode(!showAccessCode)}
  571. className="absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white"
  572. aria-label={showAccessCode ? t('virtualPrinter.accessCode.hide') : t('virtualPrinter.accessCode.reveal')}
  573. >
  574. {showAccessCode ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
  575. </button>
  576. </div>
  577. <p className="text-xs text-bambu-gray mt-1">
  578. {t('virtualPrinter.accessCode.derivedFromTargetHint')}
  579. </p>
  580. </>
  581. ) : (
  582. <>
  583. <div className="flex gap-2">
  584. <div className="relative flex-1">
  585. <input
  586. type={showAccessCode ? 'text' : 'password'}
  587. value={localAccessCode}
  588. onChange={(e) => setLocalAccessCode(e.target.value)}
  589. placeholder={printer.access_code_set ? t('virtualPrinter.accessCode.placeholderChange') : t('virtualPrinter.accessCode.placeholder')}
  590. maxLength={8}
  591. 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"
  592. />
  593. <button
  594. onClick={() => setShowAccessCode(!showAccessCode)}
  595. className="absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white"
  596. >
  597. {showAccessCode ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
  598. </button>
  599. </div>
  600. <Button
  601. onClick={handleAccessCodeChange}
  602. disabled={!localAccessCode || pendingAction === 'accessCode'}
  603. variant="primary"
  604. >
  605. {pendingAction === 'accessCode' ? <Loader2 className="w-4 h-4 animate-spin" /> : t('common.save')}
  606. </Button>
  607. </div>
  608. {localAccessCode && (
  609. <p className="text-xs text-bambu-gray mt-1">
  610. <span className={localAccessCode.length === 8 ? 'text-green-700 dark:text-green-400' : 'text-yellow-700 dark:text-yellow-400'}>
  611. {t('virtualPrinter.accessCode.charCount', { count: localAccessCode.length })}
  612. </span>
  613. </p>
  614. )}
  615. </>
  616. )}
  617. </div>
  618. )}
  619. {/* Target Printer */}
  620. <div className="pt-2 border-t border-bambu-dark-tertiary">
  621. <div className="text-white text-sm font-medium mb-2">{t('virtualPrinter.targetPrinter.title')}</div>
  622. <div className="relative">
  623. <select
  624. value={localTargetPrinterId ?? ''}
  625. onChange={(e) => {
  626. const id = parseInt(e.target.value, 10);
  627. if (!isNaN(id)) handleTargetPrinterChange(id);
  628. }}
  629. disabled={pendingAction === 'targetPrinter'}
  630. 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"
  631. >
  632. <option value="">{t('virtualPrinter.targetPrinter.placeholder')}</option>
  633. {printers?.map((p) => (
  634. <option key={p.id} value={p.id}>{p.name} ({p.ip_address})</option>
  635. ))}
  636. </select>
  637. <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none" />
  638. </div>
  639. </div>
  640. {/* Bind Interface */}
  641. <div className="pt-2 border-t border-bambu-dark-tertiary">
  642. <div className="text-white text-sm font-medium mb-1">{t('virtualPrinter.bindIp.title')}</div>
  643. <div className="relative">
  644. <select
  645. value={localBindIp}
  646. onChange={(e) => {
  647. setLocalBindIp(e.target.value);
  648. setPendingAction('bindIp');
  649. updateMutation.mutate({ bind_ip: e.target.value });
  650. }}
  651. disabled={pendingAction === 'bindIp'}
  652. 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"
  653. >
  654. <option value="">{t('virtualPrinter.bindIp.placeholder')}</option>
  655. {networkInterfaces?.map((iface) => (
  656. <option key={iface.ip} value={iface.ip}>
  657. {iface.name} ({iface.ip}){iface.is_alias ? ' [alias]' : ''} - {iface.subnet}
  658. </option>
  659. ))}
  660. </select>
  661. <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none" />
  662. </div>
  663. <p className="text-xs text-bambu-gray mt-1">{t('virtualPrinter.bindIp.hint')}</p>
  664. </div>
  665. {/* Remote Interface - always visible for configuration */}
  666. <div className="pt-2 border-t border-bambu-dark-tertiary">
  667. <div className="flex items-center gap-2 mb-1">
  668. <div className="text-white text-sm font-medium">{t('virtualPrinter.remoteInterface.title')}</div>
  669. {localRemoteInterfaceIp ? (
  670. <span className="flex items-center gap-1 text-xs text-green-700 dark:text-green-400"><Check className="w-3 h-3" /></span>
  671. ) : (
  672. <span className="flex items-center gap-1 text-xs text-bambu-gray" title={t('virtualPrinter.remoteInterface.optional')}><Info className="w-3 h-3" /></span>
  673. )}
  674. </div>
  675. <div className="relative">
  676. <select
  677. value={localRemoteInterfaceIp}
  678. onChange={(e) => handleRemoteInterfaceChange(e.target.value)}
  679. disabled={pendingAction === 'remoteInterface'}
  680. 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"
  681. >
  682. <option value="">{t('virtualPrinter.remoteInterface.placeholder')}</option>
  683. {networkInterfaces?.map((iface) => (
  684. <option key={iface.ip} value={iface.ip}>
  685. {iface.name} ({iface.ip}) - {iface.subnet}
  686. </option>
  687. ))}
  688. </select>
  689. <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none" />
  690. </div>
  691. </div>
  692. </CardContent>
  693. )}
  694. </Card>
  695. {showDeleteConfirm && (
  696. <ConfirmModal
  697. title={t('virtualPrinter.deleteConfirm.title')}
  698. message={t('virtualPrinter.deleteConfirm.message', { name: printer.name })}
  699. variant="danger"
  700. confirmText={t('common.delete')}
  701. isLoading={deleteMutation.isPending}
  702. onConfirm={() => deleteMutation.mutate()}
  703. onCancel={() => setShowDeleteConfirm(false)}
  704. />
  705. )}
  706. {showDiagnostic && (
  707. <VirtualPrinterDiagnosticModal
  708. vpId={printer.id}
  709. vpName={printer.name}
  710. onClose={() => setShowDiagnostic(false)}
  711. />
  712. )}
  713. </>
  714. );
  715. }