VirtualPrinterCard.tsx 34 KB

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