VirtualPrinterCard.tsx 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  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. {/*
  237. Clip at the border as a backstop, so a value longer than anything
  238. anticipated above lands inside the card instead of on the page
  239. background (#2808). Scoped here rather than added to `Card` itself:
  240. half the cards in the app render dropdowns and menus that deliberately
  241. paint outside their bounds, and this one has none.
  242. */}
  243. <Card className="overflow-hidden">
  244. {/* Collapsed header - always visible, clickable to expand */}
  245. <div
  246. className="px-4 py-3 flex items-center gap-3 cursor-pointer select-none"
  247. onClick={() => setExpanded(!expanded)}
  248. >
  249. <button className="text-bambu-gray flex-shrink-0">
  250. {expanded
  251. ? <ChevronDown className="w-4 h-4" />
  252. : <ChevronRight className="w-4 h-4" />
  253. }
  254. </button>
  255. <span className={`w-2 h-2 rounded-full flex-shrink-0 ${isRunning ? 'bg-green-400 animate-pulse' : 'bg-gray-500'}`} />
  256. {/*
  257. Metadata wraps rather than overflowing (#2808). Every item in this
  258. row used to be flex-shrink-0, so nothing could give and the row was
  259. as wide as its contents -- which the Card doesn't clip, so the last
  260. IP and the toggle were painted outside the card's border. The name's
  261. `truncate` didn't save it either: a flex item defaults to
  262. min-width:auto, so it couldn't shrink below its text and the
  263. ellipsis never engaged (`flex-shrink-0 truncate` on the target name
  264. was self-cancelling for the same reason).
  265. It needs three things at once to overflow, which is why it took a
  266. two-VLAN setup to surface: bind_ip and remote_interface_ip are both
  267. set only when Bambuddy and the printer are on different subnets, a
  268. printer adopted without a name is called "Printer at <ip>" (25
  269. characters of unbreakable text), and the cards sit in a 3-column
  270. grid. Wrapping keeps every value readable -- these are the addresses
  271. an operator came to this page to check, so truncating them away
  272. would trade one bug for a quieter one.
  273. */}
  274. <div className="flex-1 min-w-0 flex flex-wrap items-center gap-x-3 gap-y-1">
  275. <span className="text-white font-medium truncate max-w-full">{printer.name}</span>
  276. <span className="text-xs text-bambu-gray flex-shrink-0">{modeLabel}</span>
  277. {printer.model_name && (
  278. <span className="text-xs text-bambu-gray flex-shrink-0">{printer.model_name}</span>
  279. )}
  280. {targetPrinterName && (
  281. <span className="text-xs text-bambu-gray truncate max-w-full">
  282. {localMode === 'proxy' && <ArrowRightLeft className="w-3 h-3 inline mr-1" />}
  283. {targetPrinterName}
  284. </span>
  285. )}
  286. {localBindIp && (
  287. <span className="text-[10px] text-bambu-gray flex-shrink-0 font-mono">{localBindIp}</span>
  288. )}
  289. {localRemoteInterfaceIp && (
  290. <span className="text-[10px] text-bambu-gray flex-shrink-0 font-mono">{localRemoteInterfaceIp}</span>
  291. )}
  292. </div>
  293. <div className="ml-auto flex items-center gap-2 flex-shrink-0" onClick={(e) => e.stopPropagation()}>
  294. <button
  295. onClick={handleToggleEnabled}
  296. disabled={pendingAction === 'toggle'}
  297. className={`relative w-10 h-5 rounded-full transition-colors ${
  298. localEnabled ? 'bg-bambu-green' : 'bg-bambu-dark-tertiary'
  299. } ${pendingAction === 'toggle' ? 'opacity-50' : ''}`}
  300. >
  301. <span
  302. className={`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${
  303. localEnabled ? 'translate-x-5' : ''
  304. }`}
  305. />
  306. </button>
  307. </div>
  308. </div>
  309. {/* Expanded content */}
  310. {expanded && (
  311. <CardContent className="pt-0 space-y-4">
  312. <div className="border-t border-bambu-dark-tertiary" />
  313. {/* Name + delete */}
  314. <div className="flex items-center gap-2">
  315. <input
  316. type="text"
  317. value={localName}
  318. onChange={(e) => setLocalName(e.target.value)}
  319. onBlur={handleNameChange}
  320. onKeyDown={(e) => e.key === 'Enter' && handleNameChange()}
  321. 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"
  322. />
  323. <button
  324. onClick={() => setShowDiagnostic(true)}
  325. className="p-1.5 text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0"
  326. title={t('vpDiagnostic.runButton')}
  327. >
  328. <Stethoscope className="w-4 h-4" />
  329. </button>
  330. <button
  331. onClick={() => setShowDeleteConfirm(true)}
  332. className="p-1.5 text-bambu-gray hover:text-red-600 dark:hover:text-red-400 transition-colors flex-shrink-0"
  333. title={t('common.delete')}
  334. >
  335. <Trash2 className="w-4 h-4" />
  336. </button>
  337. </div>
  338. {/* Tailscale identity (host-level) + serial — compact info row.
  339. Shown only when this VP is marked Tailscale-exposed AND the daemon is up. */}
  340. <div className="flex items-center gap-2 -mt-2">
  341. {tailscaleFqdn && (
  342. <span className="flex items-center gap-1 text-green-700/80 dark:text-green-400/70 min-w-0">
  343. <ShieldCheck className="w-3.5 h-3.5 flex-shrink-0" />
  344. <span className="font-mono text-xs truncate">
  345. {tailscaleIp ? `${tailscaleIp} (${tailscaleFqdn})` : tailscaleFqdn}
  346. </span>
  347. <button
  348. onClick={handleCopyFqdn}
  349. className="p-0.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors flex-shrink-0"
  350. title={fqdnCopied ? t('printers.copied') : t('printers.copyToClipboard')}
  351. >
  352. {fqdnCopied ? (
  353. <Check className="w-3.5 h-3.5 text-bambu-green" />
  354. ) : (
  355. <Copy className="w-3.5 h-3.5" />
  356. )}
  357. </button>
  358. </span>
  359. )}
  360. <span className="text-xs text-bambu-gray font-mono ml-auto flex-shrink-0">{printer.serial}</span>
  361. </div>
  362. {/* Mode */}
  363. <div>
  364. <div className="text-white text-sm font-medium mb-2">{t('virtualPrinter.mode.title')}</div>
  365. <div className="grid grid-cols-2 gap-2">
  366. {(['archive', 'review', 'queue', 'proxy'] as const).map((mode) => (
  367. <button
  368. key={mode}
  369. onClick={() => handleModeChange(mode)}
  370. disabled={pendingAction === 'mode'}
  371. className={`p-2 rounded-lg border text-left transition-colors ${
  372. localMode === mode
  373. ? mode === 'proxy'
  374. ? 'border-blue-500 bg-blue-500/10'
  375. : 'border-bambu-green bg-bambu-green/10'
  376. : 'border-bambu-dark-tertiary hover:border-bambu-gray'
  377. }`}
  378. >
  379. <div className="flex items-center gap-1.5 text-white text-xs font-medium">
  380. {mode === 'proxy' && <ArrowRightLeft className="w-3 h-3" />}
  381. {t(`virtualPrinter.mode.${MODE_LABELS[mode]}`)}
  382. </div>
  383. <div className="text-[10px] text-bambu-gray">
  384. {t(`virtualPrinter.mode.${MODE_LABELS[mode]}Desc`)}
  385. </div>
  386. </button>
  387. ))}
  388. </div>
  389. </div>
  390. {/* Auto-dispatch toggle - only for queue mode */}
  391. {localMode === 'queue' && (
  392. <div className="pt-2 border-t border-bambu-dark-tertiary">
  393. <div className="flex items-center justify-between gap-3">
  394. <div className="min-w-0">
  395. <div className="text-white text-sm font-medium">{t('virtualPrinter.autoDispatch.title')}</div>
  396. <div className="text-[10px] text-bambu-gray">{t('virtualPrinter.autoDispatch.description')}</div>
  397. </div>
  398. <button
  399. onClick={() => {
  400. const newVal = !localAutoDispatch;
  401. setLocalAutoDispatch(newVal);
  402. setPendingAction('autoDispatch');
  403. updateMutation.mutate({ auto_dispatch: newVal });
  404. }}
  405. disabled={pendingAction === 'autoDispatch'}
  406. className={`relative w-10 h-5 rounded-full transition-colors flex-shrink-0 ${
  407. localAutoDispatch ? 'bg-bambu-green' : 'bg-bambu-dark-tertiary'
  408. } ${pendingAction === 'autoDispatch' ? 'opacity-50' : ''}`}
  409. >
  410. <span
  411. className={`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${
  412. localAutoDispatch ? 'translate-x-5' : ''
  413. }`}
  414. />
  415. </button>
  416. </div>
  417. </div>
  418. )}
  419. {/* Force-color-match toggle - only for queue mode (#1188) */}
  420. {localMode === 'queue' && (
  421. <div className="pt-2 border-t border-bambu-dark-tertiary">
  422. <div className="flex items-center justify-between gap-3">
  423. <div className="min-w-0">
  424. <div className="text-white text-sm font-medium">{t('virtualPrinter.queueForceColorMatch.title')}</div>
  425. <div className="text-[10px] text-bambu-gray">{t('virtualPrinter.queueForceColorMatch.description')}</div>
  426. </div>
  427. <button
  428. onClick={() => {
  429. const newVal = !localQueueForceColorMatch;
  430. setLocalQueueForceColorMatch(newVal);
  431. setPendingAction('queueForceColorMatch');
  432. updateMutation.mutate({ queue_force_color_match: newVal });
  433. }}
  434. disabled={pendingAction === 'queueForceColorMatch'}
  435. className={`relative w-10 h-5 rounded-full transition-colors flex-shrink-0 ${
  436. localQueueForceColorMatch ? 'bg-bambu-green' : 'bg-bambu-dark-tertiary'
  437. } ${pendingAction === 'queueForceColorMatch' ? 'opacity-50' : ''}`}
  438. >
  439. <span
  440. className={`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${
  441. localQueueForceColorMatch ? 'translate-x-5' : ''
  442. }`}
  443. />
  444. </button>
  445. </div>
  446. </div>
  447. )}
  448. {/* Save-AMS-mapping toggle - only for queue mode */}
  449. {localMode === 'queue' && (
  450. <div className="pt-2 border-t border-bambu-dark-tertiary">
  451. <div className="flex items-center justify-between gap-3">
  452. <div className="min-w-0">
  453. <div className="text-white text-sm font-medium">{t('virtualPrinter.saveAmsMapping.title')}</div>
  454. <div className="text-[10px] text-bambu-gray">{t('virtualPrinter.saveAmsMapping.description')}</div>
  455. </div>
  456. <button
  457. onClick={() => {
  458. const newVal = !localSaveAmsMapping;
  459. setLocalSaveAmsMapping(newVal);
  460. setPendingAction('saveAmsMapping');
  461. updateMutation.mutate({ save_ams_mapping: newVal });
  462. }}
  463. disabled={pendingAction === 'saveAmsMapping'}
  464. className={`relative w-10 h-5 rounded-full transition-colors flex-shrink-0 ${
  465. localSaveAmsMapping ? 'bg-bambu-green' : 'bg-bambu-dark-tertiary'
  466. } ${pendingAction === 'saveAmsMapping' ? 'opacity-50' : ''}`}
  467. >
  468. <span
  469. className={`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${
  470. localSaveAmsMapping ? 'translate-x-5' : ''
  471. }`}
  472. />
  473. </button>
  474. </div>
  475. </div>
  476. )}
  477. {/* G-code injection toggle - only for queue mode (#1516) */}
  478. {localMode === 'queue' && (
  479. <div className="pt-2 border-t border-bambu-dark-tertiary">
  480. <div className="flex items-center justify-between gap-3">
  481. <div className="min-w-0">
  482. <div className="text-white text-sm font-medium">{t('virtualPrinter.gcodeInjection.title')}</div>
  483. <div className="text-[10px] text-bambu-gray">{t('virtualPrinter.gcodeInjection.description')}</div>
  484. </div>
  485. <button
  486. onClick={() => {
  487. const newVal = !localGcodeInjection;
  488. setLocalGcodeInjection(newVal);
  489. setPendingAction('gcodeInjection');
  490. updateMutation.mutate({ gcode_injection: newVal });
  491. }}
  492. disabled={pendingAction === 'gcodeInjection'}
  493. className={`relative w-10 h-5 rounded-full transition-colors flex-shrink-0 ${
  494. localGcodeInjection ? 'bg-bambu-green' : 'bg-bambu-dark-tertiary'
  495. } ${pendingAction === 'gcodeInjection' ? 'opacity-50' : ''}`}
  496. >
  497. <span
  498. className={`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${
  499. localGcodeInjection ? 'translate-x-5' : ''
  500. }`}
  501. />
  502. </button>
  503. </div>
  504. </div>
  505. )}
  506. {/* Tailscale toggle */}
  507. <div className="pt-2 border-t border-bambu-dark-tertiary">
  508. <div className="flex items-center justify-between gap-3">
  509. <div className="min-w-0">
  510. <div className="text-white text-sm font-medium">{t('virtualPrinter.tailscaleDisabled.title')}</div>
  511. <div className="text-[10px] text-bambu-gray">{t('virtualPrinter.tailscaleDisabled.description')}</div>
  512. </div>
  513. <button
  514. onClick={() => {
  515. const newVal = !localTailscaleDisabled;
  516. setLocalTailscaleDisabled(newVal);
  517. setPendingAction('tailscaleDisabled');
  518. updateMutation.mutate({ tailscale_disabled: newVal });
  519. }}
  520. disabled={pendingAction === 'tailscaleDisabled'}
  521. className={`relative w-10 h-5 rounded-full transition-colors shrink-0 ${
  522. !localTailscaleDisabled ? 'bg-bambu-green' : 'bg-bambu-dark-tertiary'
  523. } ${pendingAction === 'tailscaleDisabled' ? 'opacity-50' : ''}`}
  524. >
  525. <span
  526. className={`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${
  527. !localTailscaleDisabled ? 'translate-x-5' : ''
  528. }`}
  529. />
  530. </button>
  531. </div>
  532. </div>
  533. {/* Printer Model - for non-proxy modes */}
  534. {localMode !== 'proxy' && (
  535. <div className="pt-2 border-t border-bambu-dark-tertiary">
  536. <div className="text-white text-sm font-medium mb-1">{t('virtualPrinter.model.title')}</div>
  537. <p className="text-xs text-bambu-gray mb-2">{t('virtualPrinter.model.description')}</p>
  538. <div className="relative">
  539. <select
  540. value={localModel}
  541. onChange={(e) => handleModelChange(e.target.value)}
  542. disabled={pendingAction === 'model'}
  543. 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"
  544. >
  545. {Object.entries(models).map(([code, name]) => (
  546. <option key={code} value={code}>{name} ({code})</option>
  547. ))}
  548. </select>
  549. <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none" />
  550. </div>
  551. </div>
  552. )}
  553. {/* Proxy mode: hint about using target printer's access code */}
  554. {localMode === 'proxy' && (
  555. <div className="pt-2 border-t border-bambu-dark-tertiary">
  556. <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">
  557. <Info className="w-4 h-4 text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5" />
  558. <p className="text-xs text-bambu-gray">
  559. {t('virtualPrinter.proxy.accessCodeHint')}
  560. </p>
  561. </div>
  562. </div>
  563. )}
  564. {/* Access Code - only for non-proxy modes */}
  565. {localMode !== 'proxy' && (
  566. <div className="pt-2 border-t border-bambu-dark-tertiary">
  567. <div className="flex items-center gap-2 mb-2">
  568. <div className="text-white text-sm font-medium">{t('virtualPrinter.accessCode.title')}</div>
  569. {inheritsAccessCodeFromTarget ? (
  570. <span className="flex items-center gap-1 text-xs text-blue-700 dark:text-blue-400">
  571. <Info className="w-3 h-3" />
  572. {t('virtualPrinter.accessCode.inheritedFromTarget')}
  573. </span>
  574. ) : printer.access_code_set ? (
  575. <span className="flex items-center gap-1 text-xs text-green-700 dark:text-green-400">
  576. <Check className="w-3 h-3" />
  577. {t('virtualPrinter.accessCode.isSet')}
  578. </span>
  579. ) : (
  580. <span className="flex items-center gap-1 text-xs text-yellow-700 dark:text-yellow-400">
  581. <AlertTriangle className="w-3 h-3" />
  582. {t('virtualPrinter.accessCode.notSet')}
  583. </span>
  584. )}
  585. </div>
  586. {inheritsAccessCodeFromTarget ? (
  587. <>
  588. <div className="relative">
  589. <input
  590. type={showAccessCode ? 'text' : 'password'}
  591. value={inheritedAccessCode}
  592. readOnly
  593. aria-label={t('virtualPrinter.accessCode.title')}
  594. 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"
  595. />
  596. <button
  597. onClick={() => setShowAccessCode(!showAccessCode)}
  598. className="absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white"
  599. aria-label={showAccessCode ? t('virtualPrinter.accessCode.hide') : t('virtualPrinter.accessCode.reveal')}
  600. >
  601. {showAccessCode ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
  602. </button>
  603. </div>
  604. <p className="text-xs text-bambu-gray mt-1">
  605. {t('virtualPrinter.accessCode.derivedFromTargetHint')}
  606. </p>
  607. </>
  608. ) : (
  609. <>
  610. <div className="flex gap-2">
  611. <div className="relative flex-1">
  612. <input
  613. type={showAccessCode ? 'text' : 'password'}
  614. value={localAccessCode}
  615. onChange={(e) => setLocalAccessCode(e.target.value)}
  616. placeholder={printer.access_code_set ? t('virtualPrinter.accessCode.placeholderChange') : t('virtualPrinter.accessCode.placeholder')}
  617. maxLength={8}
  618. 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"
  619. />
  620. <button
  621. onClick={() => setShowAccessCode(!showAccessCode)}
  622. className="absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white"
  623. >
  624. {showAccessCode ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
  625. </button>
  626. </div>
  627. <Button
  628. onClick={handleAccessCodeChange}
  629. disabled={!localAccessCode || pendingAction === 'accessCode'}
  630. variant="primary"
  631. >
  632. {pendingAction === 'accessCode' ? <Loader2 className="w-4 h-4 animate-spin" /> : t('common.save')}
  633. </Button>
  634. </div>
  635. {localAccessCode && (
  636. <p className="text-xs text-bambu-gray mt-1">
  637. <span className={localAccessCode.length === 8 ? 'text-green-700 dark:text-green-400' : 'text-yellow-700 dark:text-yellow-400'}>
  638. {t('virtualPrinter.accessCode.charCount', { count: localAccessCode.length })}
  639. </span>
  640. </p>
  641. )}
  642. </>
  643. )}
  644. </div>
  645. )}
  646. {/* Target Printer */}
  647. <div className="pt-2 border-t border-bambu-dark-tertiary">
  648. <div className="text-white text-sm font-medium mb-2">{t('virtualPrinter.targetPrinter.title')}</div>
  649. <div className="relative">
  650. <select
  651. value={localTargetPrinterId ?? ''}
  652. onChange={(e) => {
  653. const id = parseInt(e.target.value, 10);
  654. if (!isNaN(id)) handleTargetPrinterChange(id);
  655. }}
  656. disabled={pendingAction === 'targetPrinter'}
  657. 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"
  658. >
  659. <option value="">{t('virtualPrinter.targetPrinter.placeholder')}</option>
  660. {printers?.map((p) => (
  661. <option key={p.id} value={p.id}>{p.name} ({p.ip_address})</option>
  662. ))}
  663. </select>
  664. <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none" />
  665. </div>
  666. </div>
  667. {/* Bind Interface */}
  668. <div className="pt-2 border-t border-bambu-dark-tertiary">
  669. <div className="text-white text-sm font-medium mb-1">{t('virtualPrinter.bindIp.title')}</div>
  670. <div className="relative">
  671. <select
  672. value={localBindIp}
  673. onChange={(e) => {
  674. setLocalBindIp(e.target.value);
  675. setPendingAction('bindIp');
  676. updateMutation.mutate({ bind_ip: e.target.value });
  677. }}
  678. disabled={pendingAction === 'bindIp'}
  679. 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"
  680. >
  681. <option value="">{t('virtualPrinter.bindIp.placeholder')}</option>
  682. {networkInterfaces?.map((iface) => (
  683. <option key={iface.ip} value={iface.ip}>
  684. {iface.name} ({iface.ip}){iface.is_alias ? ' [alias]' : ''} - {iface.subnet}
  685. </option>
  686. ))}
  687. </select>
  688. <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none" />
  689. </div>
  690. <p className="text-xs text-bambu-gray mt-1">{t('virtualPrinter.bindIp.hint')}</p>
  691. </div>
  692. {/* Remote Interface - always visible for configuration */}
  693. <div className="pt-2 border-t border-bambu-dark-tertiary">
  694. <div className="flex items-center gap-2 mb-1">
  695. <div className="text-white text-sm font-medium">{t('virtualPrinter.remoteInterface.title')}</div>
  696. {localRemoteInterfaceIp ? (
  697. <span className="flex items-center gap-1 text-xs text-green-700 dark:text-green-400"><Check className="w-3 h-3" /></span>
  698. ) : (
  699. <span className="flex items-center gap-1 text-xs text-bambu-gray" title={t('virtualPrinter.remoteInterface.optional')}><Info className="w-3 h-3" /></span>
  700. )}
  701. </div>
  702. <div className="relative">
  703. <select
  704. value={localRemoteInterfaceIp}
  705. onChange={(e) => handleRemoteInterfaceChange(e.target.value)}
  706. disabled={pendingAction === 'remoteInterface'}
  707. 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"
  708. >
  709. <option value="">{t('virtualPrinter.remoteInterface.placeholder')}</option>
  710. {networkInterfaces?.map((iface) => (
  711. <option key={iface.ip} value={iface.ip}>
  712. {iface.name} ({iface.ip}) - {iface.subnet}
  713. </option>
  714. ))}
  715. </select>
  716. <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none" />
  717. </div>
  718. </div>
  719. </CardContent>
  720. )}
  721. </Card>
  722. {showDeleteConfirm && (
  723. <ConfirmModal
  724. title={t('virtualPrinter.deleteConfirm.title')}
  725. message={t('virtualPrinter.deleteConfirm.message', { name: printer.name })}
  726. variant="danger"
  727. confirmText={t('common.delete')}
  728. isLoading={deleteMutation.isPending}
  729. onConfirm={() => deleteMutation.mutate()}
  730. onCancel={() => setShowDeleteConfirm(false)}
  731. />
  732. )}
  733. {showDiagnostic && (
  734. <VirtualPrinterDiagnosticModal
  735. vpId={printer.id}
  736. vpName={printer.name}
  737. onClose={() => setShowDiagnostic(false)}
  738. />
  739. )}
  740. </>
  741. );
  742. }