Files
bambuddy/frontend/src/components/VirtualPrinterCard.tsx
T
maziggy 64899a8ca4 refactor(virtual-printer): drop Tailscale LE cert path, keep toggle informational
The Tailscale toggle was supposed to obtain a publicly-trusted Let's Encrypt
cert via `tailscale cert` so users wouldn't need to import Bambuddy's CA into
the slicer. End-to-end testing showed this was always going to fail:

  - Bambu Studio and OrcaSlicer refuse hostname input in the Add Printer
    dialog (IP-only).
  - Their printer-MQTT trust path validates only against the bundled BBL CA
    store (`printer.cer`), NOT the system trust store. Confirmed against
    ClusterM/open-bambu-networking's clean-room reimplementation:
    `mosquitto_tls_set(BBL_CA)` + `verify_peer=1` + `tls_insecure=true` —
    chain validation against BBL CA only, hostname check intentionally
    skipped (because Bambu's printer cert CN is the device serial).
  - LE certs don't chain to BBL CA, so the slicer rejects with the
    well-known "-1" before any hostname/IP logic runs.

The cert-import step is unavoidable; LE provisioning was dead code for slicer
connections. Pivot:

  - Toggle stays as an informational marker — when ON, the VP card surfaces
    the host's Tailscale IP + MagicDNS hostname so users know what to paste
    into the slicer.
  - Cert is always self-signed (signed by `bbl_ca`).
  - Tailscale exposure is via the existing bind_ip dropdown, which already
    includes `tailscale0` IPs.
  - Tailscale's role is strictly network reach — same trust burden as LAN.

Backend cuts:

  - `tailscale.py`: `provision_cert`, `ensure_cert`, `cert_needs_renewal`,
    `_FQDN_RE`, `_HTTPS_DISABLED_RE`, `TS_CERT_EXPIRY_THRESHOLD_DAYS`,
    `cryptography` import. Keep `get_status` and `TailscaleStatus`.
  - `certificate.py`: `ts_cert_path`, `ts_key_path`, `use_tailscale_cert`.
  - `manager.py`: `tailscale_fqdn` field, `_cert_renewal_task`,
    `_cert_restart_task`, `_cert_renewal_loop`, `_restart_for_cert_renewal`,
    `_cancel_renewal_task`, `_cancel_restart_task`. Simplify
    `_resolve_cert_and_advertise` to a sync method that just generates the
    self-signed cert. Drop `tailscale_disabled` from the change-detection
    diff (toggle is informational — no service restart needed).
  - `routes/virtual_printers.py` + `routes/settings.py`: drop the
    `tailscale_not_available` 409 guard on toggle-enable.

Frontend cuts:

  - `VirtualPrinterCard.tsx`: FQDN/IP display sourced from
    `multiVirtualPrinterApi.getTailscaleStatus()` (host-level) when toggle
    is ON, instead of `printer.status.tailscale_fqdn` (cert side-effect,
    no longer populated). Drop the `tailscale_not_available` toast handler.
  - `api/client.ts`: drop `tailscale_fqdn` from the VP status type.
  - i18n: rewrite `tailscaleDisabled.description` in all 8 locales to drop
    the "no cert import" promise. Remove `toast.tailscaleNotAvailable` key.

Docs:

  - Wiki `features/virtual-printer.md`: rewrite the entire Tailscale section
    — remove the LE-cert + HTTPS-Certs-toggle + tailscale-cert-operator
    steps, document the toggle as informational, keep the Docker socket
    mount + LXC TUN troubleshooting (those still apply for daemon
    reachability).
  - README: drop "the Tailscale benefit here is the tunnel, not cert-import
    elimination" framing in favour of "surfaces the IP for paste into
    slicer; CA import unchanged because BBL CA store, not system trust
    store, is what gets validated".

Tests:

  - `test_tailscale.py`: reduced to surviving `get_status` cases (binary
    missing, command fails, success, empty DNSName, malformed JSON).
  - `test_virtual_printer.py::test_sync_from_db_restarts_on_tailscale_disabled_change`
    → `test_sync_from_db_does_not_restart_on_tailscale_toggle` (toggle is
    informational; `remove_instance` must NOT be called).
  - `test_virtual_printer_api.py::TestVirtualPrinterTailscaleGuardAPI` →
    `TestVirtualPrinterTailscaleToggleAPI` (single test asserts both
    directions succeed and daemon is never consulted).
  - `VirtualPrinterCard.test.tsx`: mock now stubs `getTailscaleStatus`;
    FQDN-copy block drives data through that query.

DB column `tailscale_disabled` is kept (persists toggle state) — Postgres-
safe column drop is harder; future cleanup can remove if the toggle goes
away entirely. LE cert files on disk (`virtual_printer_ts.{crt,key}`) are
left in place per VP — harmless residue, manual cleanup if desired.

Verified: ruff clean, 2484 backend unit tests pass, 17 frontend VP-card
tests pass, frontend build succeeds, live service restart confirms VPs
serve `issuer=CN=Virtual Printer CA` on the Tailscale interface — slicer
trusts the user-imported bambuddy CA and skips hostname checks, so MQTT
connection succeeds end-to-end.
2026-05-03 14:58:29 +02:00

631 lines
28 KiB
TypeScript

import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useMutation, useQueryClient, useQuery } from '@tanstack/react-query';
import {
Loader2, Check, AlertTriangle, Eye, EyeOff, Info,
ChevronDown, ChevronRight, ArrowRightLeft, Trash2, ShieldCheck, Copy,
} from 'lucide-react';
import { api, multiVirtualPrinterApi } from '../api/client';
import type { VirtualPrinterConfig } from '../api/client';
import { Card, CardContent } from './Card';
import { Button } from './Button';
import { ConfirmModal } from './ConfirmModal';
import { useToast } from '../contexts/ToastContext';
type LocalMode = 'immediate' | 'review' | 'print_queue' | 'proxy';
const MODE_LABELS: Record<string, string> = {
immediate: 'archive',
review: 'review',
print_queue: 'queue',
proxy: 'proxy',
};
interface VirtualPrinterCardProps {
printer: VirtualPrinterConfig;
models: Record<string, string>;
}
export function VirtualPrinterCard({ printer, models }: VirtualPrinterCardProps) {
const { t } = useTranslation();
const queryClient = useQueryClient();
const { showToast } = useToast();
const [expanded, setExpanded] = useState(true);
const [localEnabled, setLocalEnabled] = useState(printer.enabled);
const [localName, setLocalName] = useState(printer.name);
const [localAccessCode, setLocalAccessCode] = useState('');
const [localMode, setLocalMode] = useState<LocalMode>(
(printer.mode === 'queue' ? 'review' : printer.mode) as LocalMode
);
const [localTargetPrinterId, setLocalTargetPrinterId] = useState<number | null>(printer.target_printer_id);
const [localBindIp, setLocalBindIp] = useState(printer.bind_ip || '');
const [localRemoteInterfaceIp, setLocalRemoteInterfaceIp] = useState(printer.remote_interface_ip || '');
const [localModel, setLocalModel] = useState(printer.model || '');
const [localAutoDispatch, setLocalAutoDispatch] = useState(printer.auto_dispatch ?? true);
const [localQueueForceColorMatch, setLocalQueueForceColorMatch] = useState(printer.queue_force_color_match ?? false);
const [localTailscaleDisabled, setLocalTailscaleDisabled] = useState(printer.tailscale_disabled ?? true);
const [showAccessCode, setShowAccessCode] = useState(false);
const [pendingAction, setPendingAction] = useState<string | null>(null);
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const [fqdnCopied, setFqdnCopied] = useState(false);
// Host-level Tailscale identity (same for every VP) — shown inline on the card when
// the user has marked this VP as "exposed over Tailscale". Cert handling does NOT
// depend on this toggle; the slicer trusts the bambuddy CA the user imports once.
const { data: tailscaleStatus } = useQuery({
queryKey: ['tailscale-status'],
queryFn: multiVirtualPrinterApi.getTailscaleStatus,
enabled: !localTailscaleDisabled,
staleTime: 60_000,
});
const tailscaleFqdn = tailscaleStatus?.available ? tailscaleStatus.fqdn : '';
const tailscaleIp = tailscaleStatus?.available ? tailscaleStatus.tailscale_ips?.[0] ?? '' : '';
const handleCopyFqdn = async (e: React.MouseEvent) => {
e.stopPropagation();
const fqdn = tailscaleFqdn;
if (!fqdn) return;
let ok = false;
// Modern API — only works in secure contexts (HTTPS / localhost).
if (navigator.clipboard && window.isSecureContext) {
try {
await navigator.clipboard.writeText(fqdn);
ok = true;
} catch {
// fall through to legacy
}
}
// Legacy fallback for HTTP (common when Bambuddy is reached over LAN / tailnet IP).
if (!ok) {
const ta = document.createElement('textarea');
ta.value = fqdn;
ta.style.position = 'fixed';
ta.style.opacity = '0';
document.body.appendChild(ta);
try {
ta.select();
ok = document.execCommand('copy');
} catch {
ok = false;
} finally {
if (ta.parentNode) ta.parentNode.removeChild(ta);
}
}
if (ok) {
setFqdnCopied(true);
showToast(t('printers.copied'));
setTimeout(() => setFqdnCopied(false), 2000);
} else {
showToast(t('virtualPrinter.toast.copyFailed'), 'error');
}
};
// Sync local state when props change (e.g., after backend auto-disable)
useEffect(() => {
if (!pendingAction) {
setLocalEnabled(printer.enabled);
setLocalMode((printer.mode === 'queue' ? 'review' : printer.mode) as LocalMode);
setLocalName(printer.name);
setLocalTargetPrinterId(printer.target_printer_id);
setLocalBindIp(printer.bind_ip || '');
setLocalRemoteInterfaceIp(printer.remote_interface_ip || '');
setLocalModel(printer.model || '');
setLocalAutoDispatch(printer.auto_dispatch ?? true);
setLocalQueueForceColorMatch(printer.queue_force_color_match ?? false);
setLocalTailscaleDisabled(printer.tailscale_disabled ?? true);
}
}, [printer, pendingAction]);
// Fetch printers for dropdown
const { data: printers } = useQuery({
queryKey: ['printers'],
queryFn: api.getPrinters,
});
// Fetch network interfaces
const { data: networkInterfaces } = useQuery({
queryKey: ['network-interfaces'],
queryFn: () => api.getNetworkInterfaces().then(res => res.interfaces),
});
const updateMutation = useMutation({
mutationFn: (data: Parameters<typeof multiVirtualPrinterApi.update>[1]) =>
multiVirtualPrinterApi.update(printer.id, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['virtual-printers'] });
showToast(t('virtualPrinter.toast.updated'));
setPendingAction(null);
},
onError: (error: Error) => {
showToast(error.message || t('virtualPrinter.toast.failedToUpdate'), 'error');
setLocalEnabled(printer.enabled);
setLocalMode((printer.mode === 'queue' ? 'review' : printer.mode) as LocalMode);
setLocalTargetPrinterId(printer.target_printer_id);
setLocalBindIp(printer.bind_ip || '');
setLocalTailscaleDisabled(printer.tailscale_disabled ?? true);
setPendingAction(null);
},
});
const deleteMutation = useMutation({
mutationFn: () => multiVirtualPrinterApi.remove(printer.id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['virtual-printers'] });
showToast(t('virtualPrinter.toast.deleted'));
setShowDeleteConfirm(false);
},
onError: (error: Error) => {
showToast(error.message || t('virtualPrinter.toast.failedToDelete'), 'error');
setShowDeleteConfirm(false);
},
});
const handleToggleEnabled = (e: React.MouseEvent) => {
e.stopPropagation();
const newEnabled = !localEnabled;
if (newEnabled) {
if (!localBindIp) {
showToast(t('virtualPrinter.toast.bindIpRequired'), 'error');
return;
}
if (localMode === 'proxy') {
if (!localTargetPrinterId) {
showToast(t('virtualPrinter.toast.targetPrinterRequired'), 'error');
return;
}
} else {
if (!localAccessCode && !printer.access_code_set) {
showToast(t('virtualPrinter.toast.accessCodeRequired'), 'error');
return;
}
}
}
setLocalEnabled(newEnabled);
setPendingAction('toggle');
updateMutation.mutate({ enabled: newEnabled });
};
const handleNameChange = () => {
if (!localName.trim()) return;
setPendingAction('name');
updateMutation.mutate({ name: localName.trim() });
};
const handleAccessCodeChange = () => {
if (!localAccessCode) {
showToast(t('virtualPrinter.toast.accessCodeEmpty'), 'error');
return;
}
if (localAccessCode.length !== 8) {
showToast(t('virtualPrinter.toast.accessCodeLength'), 'error');
return;
}
setPendingAction('accessCode');
updateMutation.mutate({ access_code: localAccessCode });
setLocalAccessCode('');
};
const handleModeChange = (mode: LocalMode) => {
setLocalMode(mode);
setPendingAction('mode');
updateMutation.mutate({ mode });
};
const handleModelChange = (model: string) => {
setLocalModel(model);
setPendingAction('model');
updateMutation.mutate({ model });
};
const handleTargetPrinterChange = (printerId: number) => {
setLocalTargetPrinterId(printerId);
setPendingAction('targetPrinter');
updateMutation.mutate({ target_printer_id: printerId });
};
const handleRemoteInterfaceChange = (ip: string) => {
setLocalRemoteInterfaceIp(ip);
setPendingAction('remoteInterface');
updateMutation.mutate({ remote_interface_ip: ip });
};
const isRunning = printer.status?.running || false;
const modeLabel = t(`virtualPrinter.mode.${MODE_LABELS[localMode] || 'archive'}`);
const targetPrinterName = printers?.find(p => p.id === localTargetPrinterId)?.name;
return (
<>
<Card>
{/* Collapsed header - always visible, clickable to expand */}
<div
className="px-4 py-3 flex items-center gap-3 cursor-pointer select-none"
onClick={() => setExpanded(!expanded)}
>
<button className="text-bambu-gray flex-shrink-0">
{expanded
? <ChevronDown className="w-4 h-4" />
: <ChevronRight className="w-4 h-4" />
}
</button>
<span className={`w-2 h-2 rounded-full flex-shrink-0 ${isRunning ? 'bg-green-400 animate-pulse' : 'bg-gray-500'}`} />
<span className="text-white font-medium truncate">{printer.name}</span>
<span className="text-xs text-bambu-gray flex-shrink-0">{modeLabel}</span>
{printer.model_name && (
<span className="text-xs text-bambu-gray flex-shrink-0">{printer.model_name}</span>
)}
{targetPrinterName && (
<span className="text-xs text-bambu-gray flex-shrink-0 truncate">
{localMode === 'proxy' && <ArrowRightLeft className="w-3 h-3 inline mr-1" />}
{targetPrinterName}
</span>
)}
{localBindIp && (
<span className="text-[10px] text-bambu-gray flex-shrink-0 font-mono">{localBindIp}</span>
)}
{localRemoteInterfaceIp && (
<span className="text-[10px] text-bambu-gray flex-shrink-0 font-mono">{localRemoteInterfaceIp}</span>
)}
<div className="ml-auto flex items-center gap-2 flex-shrink-0" onClick={(e) => e.stopPropagation()}>
<button
onClick={handleToggleEnabled}
disabled={pendingAction === 'toggle'}
className={`relative w-10 h-5 rounded-full transition-colors ${
localEnabled ? 'bg-bambu-green' : 'bg-bambu-dark-tertiary'
} ${pendingAction === 'toggle' ? 'opacity-50' : ''}`}
>
<span
className={`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${
localEnabled ? 'translate-x-5' : ''
}`}
/>
</button>
</div>
</div>
{/* Expanded content */}
{expanded && (
<CardContent className="pt-0 space-y-4">
<div className="border-t border-bambu-dark-tertiary" />
{/* Name + delete */}
<div className="flex items-center gap-2">
<input
type="text"
value={localName}
onChange={(e) => setLocalName(e.target.value)}
onBlur={handleNameChange}
onKeyDown={(e) => e.key === 'Enter' && handleNameChange()}
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"
/>
<button
onClick={() => setShowDeleteConfirm(true)}
className="p-1.5 text-bambu-gray hover:text-red-400 transition-colors flex-shrink-0"
title={t('common.delete')}
>
<Trash2 className="w-4 h-4" />
</button>
</div>
{/* Tailscale identity (host-level) + serial — compact info row.
Shown only when this VP is marked Tailscale-exposed AND the daemon is up. */}
<div className="flex items-center gap-2 -mt-2">
{tailscaleFqdn && (
<span className="flex items-center gap-1 text-green-400/70 min-w-0">
<ShieldCheck className="w-3.5 h-3.5 flex-shrink-0" />
<span className="font-mono text-xs truncate">
{tailscaleIp ? `${tailscaleIp} (${tailscaleFqdn})` : tailscaleFqdn}
</span>
<button
onClick={handleCopyFqdn}
className="p-0.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors flex-shrink-0"
title={fqdnCopied ? t('printers.copied') : t('printers.copyToClipboard')}
>
{fqdnCopied ? (
<Check className="w-3.5 h-3.5 text-bambu-green" />
) : (
<Copy className="w-3.5 h-3.5" />
)}
</button>
</span>
)}
<span className="text-xs text-bambu-gray font-mono ml-auto flex-shrink-0">{printer.serial}</span>
</div>
{/* Mode */}
<div>
<div className="text-white text-sm font-medium mb-2">{t('virtualPrinter.mode.title')}</div>
<div className="grid grid-cols-2 gap-2">
{(['immediate', 'review', 'print_queue', 'proxy'] as const).map((mode) => (
<button
key={mode}
onClick={() => handleModeChange(mode)}
disabled={pendingAction === 'mode'}
className={`p-2 rounded-lg border text-left transition-colors ${
localMode === mode
? mode === 'proxy'
? 'border-blue-500 bg-blue-500/10'
: 'border-bambu-green bg-bambu-green/10'
: 'border-bambu-dark-tertiary hover:border-bambu-gray'
}`}
>
<div className="flex items-center gap-1.5 text-white text-xs font-medium">
{mode === 'proxy' && <ArrowRightLeft className="w-3 h-3" />}
{t(`virtualPrinter.mode.${MODE_LABELS[mode]}`)}
</div>
<div className="text-[10px] text-bambu-gray">
{t(`virtualPrinter.mode.${MODE_LABELS[mode]}Desc`)}
</div>
</button>
))}
</div>
</div>
{/* Auto-dispatch toggle - only for print_queue mode */}
{localMode === 'print_queue' && (
<div className="pt-2 border-t border-bambu-dark-tertiary">
<div className="flex items-center justify-between gap-3">
<div className="min-w-0">
<div className="text-white text-sm font-medium">{t('virtualPrinter.autoDispatch.title')}</div>
<div className="text-[10px] text-bambu-gray">{t('virtualPrinter.autoDispatch.description')}</div>
</div>
<button
onClick={() => {
const newVal = !localAutoDispatch;
setLocalAutoDispatch(newVal);
setPendingAction('autoDispatch');
updateMutation.mutate({ auto_dispatch: newVal });
}}
disabled={pendingAction === 'autoDispatch'}
className={`relative w-10 h-5 rounded-full transition-colors flex-shrink-0 ${
localAutoDispatch ? 'bg-bambu-green' : 'bg-bambu-dark-tertiary'
} ${pendingAction === 'autoDispatch' ? 'opacity-50' : ''}`}
>
<span
className={`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${
localAutoDispatch ? 'translate-x-5' : ''
}`}
/>
</button>
</div>
</div>
)}
{/* Force-color-match toggle - only for print_queue mode (#1188) */}
{localMode === 'print_queue' && (
<div className="pt-2 border-t border-bambu-dark-tertiary">
<div className="flex items-center justify-between gap-3">
<div className="min-w-0">
<div className="text-white text-sm font-medium">{t('virtualPrinter.queueForceColorMatch.title')}</div>
<div className="text-[10px] text-bambu-gray">{t('virtualPrinter.queueForceColorMatch.description')}</div>
</div>
<button
onClick={() => {
const newVal = !localQueueForceColorMatch;
setLocalQueueForceColorMatch(newVal);
setPendingAction('queueForceColorMatch');
updateMutation.mutate({ queue_force_color_match: newVal });
}}
disabled={pendingAction === 'queueForceColorMatch'}
className={`relative w-10 h-5 rounded-full transition-colors flex-shrink-0 ${
localQueueForceColorMatch ? 'bg-bambu-green' : 'bg-bambu-dark-tertiary'
} ${pendingAction === 'queueForceColorMatch' ? 'opacity-50' : ''}`}
>
<span
className={`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${
localQueueForceColorMatch ? 'translate-x-5' : ''
}`}
/>
</button>
</div>
</div>
)}
{/* Tailscale toggle */}
<div className="pt-2 border-t border-bambu-dark-tertiary">
<div className="flex items-center justify-between gap-3">
<div className="min-w-0">
<div className="text-white text-sm font-medium">{t('virtualPrinter.tailscaleDisabled.title')}</div>
<div className="text-[10px] text-bambu-gray">{t('virtualPrinter.tailscaleDisabled.description')}</div>
</div>
<button
onClick={() => {
const newVal = !localTailscaleDisabled;
setLocalTailscaleDisabled(newVal);
setPendingAction('tailscaleDisabled');
updateMutation.mutate({ tailscale_disabled: newVal });
}}
disabled={pendingAction === 'tailscaleDisabled'}
className={`relative w-10 h-5 rounded-full transition-colors shrink-0 ${
!localTailscaleDisabled ? 'bg-bambu-green' : 'bg-bambu-dark-tertiary'
} ${pendingAction === 'tailscaleDisabled' ? 'opacity-50' : ''}`}
>
<span
className={`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${
!localTailscaleDisabled ? 'translate-x-5' : ''
}`}
/>
</button>
</div>
</div>
{/* Printer Model - for non-proxy modes */}
{localMode !== 'proxy' && (
<div className="pt-2 border-t border-bambu-dark-tertiary">
<div className="text-white text-sm font-medium mb-1">{t('virtualPrinter.model.title')}</div>
<p className="text-xs text-bambu-gray mb-2">{t('virtualPrinter.model.description')}</p>
<div className="relative">
<select
value={localModel}
onChange={(e) => handleModelChange(e.target.value)}
disabled={pendingAction === 'model'}
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"
>
{Object.entries(models).map(([code, name]) => (
<option key={code} value={code}>{name} ({code})</option>
))}
</select>
<ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none" />
</div>
</div>
)}
{/* Proxy mode: hint about using target printer's access code */}
{localMode === 'proxy' && (
<div className="pt-2 border-t border-bambu-dark-tertiary">
<div className="flex items-start gap-2 p-2 rounded bg-blue-500/10 border border-blue-500/30">
<Info className="w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5" />
<p className="text-xs text-bambu-gray">
{t('virtualPrinter.proxy.accessCodeHint')}
</p>
</div>
</div>
)}
{/* Access Code - only for non-proxy modes */}
{localMode !== 'proxy' && (
<div className="pt-2 border-t border-bambu-dark-tertiary">
<div className="flex items-center gap-2 mb-2">
<div className="text-white text-sm font-medium">{t('virtualPrinter.accessCode.title')}</div>
{printer.access_code_set ? (
<span className="flex items-center gap-1 text-xs text-green-400">
<Check className="w-3 h-3" />
{t('virtualPrinter.accessCode.isSet')}
</span>
) : (
<span className="flex items-center gap-1 text-xs text-yellow-400">
<AlertTriangle className="w-3 h-3" />
{t('virtualPrinter.accessCode.notSet')}
</span>
)}
</div>
<div className="flex gap-2">
<div className="relative flex-1">
<input
type={showAccessCode ? 'text' : 'password'}
value={localAccessCode}
onChange={(e) => setLocalAccessCode(e.target.value)}
placeholder={printer.access_code_set ? t('virtualPrinter.accessCode.placeholderChange') : t('virtualPrinter.accessCode.placeholder')}
maxLength={8}
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"
/>
<button
onClick={() => setShowAccessCode(!showAccessCode)}
className="absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white"
>
{showAccessCode ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
</button>
</div>
<Button
onClick={handleAccessCodeChange}
disabled={!localAccessCode || pendingAction === 'accessCode'}
variant="primary"
>
{pendingAction === 'accessCode' ? <Loader2 className="w-4 h-4 animate-spin" /> : t('common.save')}
</Button>
</div>
{localAccessCode && (
<p className="text-xs text-bambu-gray mt-1">
<span className={localAccessCode.length === 8 ? 'text-green-400' : 'text-yellow-400'}>
{t('virtualPrinter.accessCode.charCount', { count: localAccessCode.length })}
</span>
</p>
)}
</div>
)}
{/* Target Printer */}
<div className="pt-2 border-t border-bambu-dark-tertiary">
<div className="text-white text-sm font-medium mb-2">{t('virtualPrinter.targetPrinter.title')}</div>
<div className="relative">
<select
value={localTargetPrinterId ?? ''}
onChange={(e) => {
const id = parseInt(e.target.value, 10);
if (!isNaN(id)) handleTargetPrinterChange(id);
}}
disabled={pendingAction === 'targetPrinter'}
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"
>
<option value="">{t('virtualPrinter.targetPrinter.placeholder')}</option>
{printers?.map((p) => (
<option key={p.id} value={p.id}>{p.name} ({p.ip_address})</option>
))}
</select>
<ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none" />
</div>
</div>
{/* Bind Interface */}
<div className="pt-2 border-t border-bambu-dark-tertiary">
<div className="text-white text-sm font-medium mb-1">{t('virtualPrinter.bindIp.title')}</div>
<div className="relative">
<select
value={localBindIp}
onChange={(e) => {
setLocalBindIp(e.target.value);
setPendingAction('bindIp');
updateMutation.mutate({ bind_ip: e.target.value });
}}
disabled={pendingAction === 'bindIp'}
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"
>
<option value="">{t('virtualPrinter.bindIp.placeholder')}</option>
{networkInterfaces?.map((iface) => (
<option key={iface.ip} value={iface.ip}>
{iface.name} ({iface.ip}){iface.is_alias ? ' [alias]' : ''} - {iface.subnet}
</option>
))}
</select>
<ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none" />
</div>
<p className="text-xs text-bambu-gray mt-1">{t('virtualPrinter.bindIp.hint')}</p>
</div>
{/* Remote Interface - always visible for configuration */}
<div className="pt-2 border-t border-bambu-dark-tertiary">
<div className="flex items-center gap-2 mb-1">
<div className="text-white text-sm font-medium">{t('virtualPrinter.remoteInterface.title')}</div>
{localRemoteInterfaceIp ? (
<span className="flex items-center gap-1 text-xs text-green-400"><Check className="w-3 h-3" /></span>
) : (
<span className="flex items-center gap-1 text-xs text-bambu-gray" title={t('virtualPrinter.remoteInterface.optional')}><Info className="w-3 h-3" /></span>
)}
</div>
<div className="relative">
<select
value={localRemoteInterfaceIp}
onChange={(e) => handleRemoteInterfaceChange(e.target.value)}
disabled={pendingAction === 'remoteInterface'}
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"
>
<option value="">{t('virtualPrinter.remoteInterface.placeholder')}</option>
{networkInterfaces?.map((iface) => (
<option key={iface.ip} value={iface.ip}>
{iface.name} ({iface.ip}) - {iface.subnet}
</option>
))}
</select>
<ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none" />
</div>
</div>
</CardContent>
)}
</Card>
{showDeleteConfirm && (
<ConfirmModal
title={t('virtualPrinter.deleteConfirm.title')}
message={t('virtualPrinter.deleteConfirm.message', { name: printer.name })}
variant="danger"
confirmText={t('common.delete')}
isLoading={deleteMutation.isPending}
onConfirm={() => deleteMutation.mutate()}
onCancel={() => setShowDeleteConfirm(false)}
/>
)}
</>
);
}