import { useEffect, useMemo, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { X, Loader2, Printer, CheckSquare, Square, Search, Download } from 'lucide-react'; import { api, ApiError, DEFAULT_SPOOL_LABEL_FIELDS, SPOOL_LABEL_FIELDS, type LabelSheetLayout, type SavedLabelTemplate, type SpoolLabelField, type SpoolLabelRequestTemplate, type SpoolLabelTemplate, type InventorySpool, } from '../api/client'; import { Button } from './Button'; import { ConfirmModal } from './ConfirmModal'; import { LabelSheetDiagram, LabelSheetLayoutEditor } from './LabelSheetLayoutEditor'; import { useAuth } from '../contexts/AuthContext'; import { useToast } from '../contexts/ToastContext'; import { DEFAULT_LAYOUT, MAX_PNG_SHEET_PAGES_X_DPI, draftFromLayout, formatMm, isLayoutDraft, layoutProblem, parseDraft, sheetPageCount, type LayoutDraft, } from '../utils/labelSheetLayout'; import { getSwatchStyle, resolveSpoolColorName } from '../utils/colors'; import { useColorCatalogVersion } from '../hooks/useColorCatalogVersion'; /** Subset of InventorySpool the modal needs for checkbox rendering. */ type SpoolForLabel = Pick< InventorySpool, 'id' | 'material' | 'subtype' | 'brand' | 'color_name' | 'color_name_is_synthesized' | 'rgba' >; interface LabelTemplatePickerModalProps { isOpen: boolean; onClose: () => void; /** All spools the modal can choose from. Typically the page's current * filter result so the modal stays consistent with what the user sees. */ availableSpools: SpoolForLabel[]; /** IDs to pre-check when the modal opens. Per-card icon passes a single ID; * the bulk header button passes every visible ID so the user lands in * "all checked" and refines downward. */ initialSelectedIds: number[]; spoolmanMode: boolean; } interface TemplateOption { value: SpoolLabelTemplate; i18nKey: string; fallbackLabel: string; fallbackHint: string; } const TEMPLATE_OPTIONS: TemplateOption[] = [ { value: 'ams_holder_74x33', i18nKey: 'amsHolderSmall', fallbackLabel: 'AMS holder — small (74 × 33 mm)', fallbackHint: 'Single label per page; matches the printable label from MakerWorld model 752566 (AMS Filament Label Holder).', }, { value: 'ams_holder_75x55', i18nKey: 'amsHolderLarge', fallbackLabel: 'AMS holder — large (75 × 55 mm)', fallbackHint: 'Single label per page; fits the cardstock-insert variant of the AMS Filament Label Holder. Roomy enough for swatch, brand, material, ID, and QR code.', }, { value: 'box_40x30', i18nKey: 'box40x30', fallbackLabel: 'Box label (40 × 30 mm)', fallbackHint: 'Single label per page; common DK/Brother roll size, good for filament-bag and storage-bin labels.', }, { value: 'box_62x29', i18nKey: 'box', fallbackLabel: 'Box label (62 × 29 mm)', fallbackHint: 'Single label per page; sized for Brother PT/QL and Dymo small labels.', }, { value: 'avery_l7160', i18nKey: 'averyL7160', fallbackLabel: 'Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)', fallbackHint: 'EU sheet stock; 21 labels per A4 page.', }, { value: 'avery_5160', i18nKey: 'avery5160', fallbackLabel: 'Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)', fallbackHint: 'US sheet stock; 30 labels per Letter page.', }, ]; const SHEET_CAPACITIES: Partial> = { avery_l7160: 21, avery_5160: 30, }; type OutputFormat = 'pdf' | 'png'; type PngDpi = 203 | 300 | 600; const PNG_DPIS: PngDpi[] = [203, 300, 600]; // What the checkboxes read, keyed by SpoolLabelField (#2981). const FIELD_LABELS: Record = { brand: { i18nKey: 'brand', fallback: 'Brand' }, material: { i18nKey: 'material', fallback: 'Material and subtype' }, hex: { i18nKey: 'hex', fallback: 'Colour code' }, name: { i18nKey: 'name', fallback: 'Colour or filament name' }, location: { i18nKey: 'location', fallback: 'Storage location' }, material_number: { i18nKey: 'materialNumber', fallback: 'Material number' }, temps: { i18nKey: 'temps', fallback: 'Nozzle temperature' }, weight: { i18nKey: 'weight', fallback: 'Net weight' }, note: { i18nKey: 'note', fallback: 'Note' }, added: { i18nKey: 'added', fallback: 'Date added' }, qr: { i18nKey: 'qr', fallback: 'QR code' }, spool_id: { i18nKey: 'spoolId', fallback: 'Spool ID' }, }; // Remembered per browser. Printing only needs inventory access, and a server // setting would need settings access to save. const PREFS_STORAGE_KEY = 'bambuddy-label-print-options'; // What the label size dropdown holds: a built-in template, a one-off custom // sheet, or a saved template by id (#3296). type TemplateChoice = SpoolLabelTemplate | 'custom' | `saved:${number}`; const SAVED_TEMPLATES_KEY = ['labelTemplates']; function savedChoice(id: number): TemplateChoice { return `saved:${id}`; } function savedIdOf(choice: TemplateChoice): number | null { return choice.startsWith('saved:') ? Number(choice.slice('saved:'.length)) : null; } function isTemplateChoice(value: unknown): value is TemplateChoice { if (typeof value !== 'string') return false; if (value === 'custom' || /^saved:[1-9]\d*$/.test(value)) return true; return TEMPLATE_OPTIONS.some((o) => o.value === value); } interface LabelPrefs { template: TemplateChoice; /** Chosen lines per template: a 40 × 30 roll and an A4 sheet fit different amounts. */ fields: Partial>; /** The one-off custom sheet, as last typed. */ customDraft: LayoutDraft; monochrome: boolean; format: OutputFormat; dpi: PngDpi; } const DEFAULT_PREFS: LabelPrefs = { template: TEMPLATE_OPTIONS[0].value, fields: {}, customDraft: draftFromLayout(DEFAULT_LAYOUT), monochrome: false, format: 'pdf', dpi: 300, }; function loadPrefs(): LabelPrefs { let raw: unknown; try { raw = JSON.parse(localStorage.getItem(PREFS_STORAGE_KEY) ?? 'null'); } catch { return DEFAULT_PREFS; } if (!raw || typeof raw !== 'object') return DEFAULT_PREFS; const r = raw as Partial>; const fields: LabelPrefs['fields'] = {}; if (r.fields && typeof r.fields === 'object') { for (const [tpl, list] of Object.entries(r.fields as Record)) { if (!isTemplateChoice(tpl) || !Array.isArray(list)) continue; fields[tpl] = list.filter((f): f is SpoolLabelField => (SPOOL_LABEL_FIELDS as readonly string[]).includes(f), ); } } return { template: isTemplateChoice(r.template) ? r.template : DEFAULT_PREFS.template, fields, customDraft: isLayoutDraft(r.customDraft) ? r.customDraft : DEFAULT_PREFS.customDraft, monochrome: r.monochrome === true, format: r.format === 'png' ? 'png' : 'pdf', dpi: PNG_DPIS.includes(r.dpi as PngDpi) ? (r.dpi as PngDpi) : DEFAULT_PREFS.dpi, }; } function savePrefs(prefs: LabelPrefs): void { try { localStorage.setItem(PREFS_STORAGE_KEY, JSON.stringify(prefs)); } catch { // Private mode or storage disabled: the options just aren't remembered. } } function fieldsFor(prefs: LabelPrefs, template: TemplateChoice): SpoolLabelField[] { return prefs.fields[template] ?? DEFAULT_SPOOL_LABEL_FIELDS; } function openBlobInNewTab(blob: Blob): void { const url = window.URL.createObjectURL(blob); // Do NOT pass `noopener,noreferrer`: per the WindowFeatures spec, `noopener` // forces window.open to return `null` even on success, which made the // `if (!win)` popup-block fallback below fire on EVERY click — so the blob // tab opened (downloading a random-named PDF on systems without an inline // viewer) AND the `` fallback fired (downloading a second copy // named bambuddy-labels.pdf). Two identical PDFs per click — issue #1628. // The blob is same-origin, the destination is a passive PDF tab with no // script context, and `noreferrer` is a no-op for blob URLs, so dropping // these flags has no security impact. const win = window.open(url, '_blank'); if (!win) { const a = document.createElement('a'); a.href = url; a.download = 'bambuddy-labels.pdf'; document.body.appendChild(a); a.click(); document.body.removeChild(a); } setTimeout(() => window.URL.revokeObjectURL(url), 60_000); } /** Save a PNG, or a ZIP of PNGs when there were several pages. */ function downloadBlob(blob: Blob, template: SpoolLabelRequestTemplate): void { const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `bambuddy-labels-${template}.${blob.type === 'application/zip' ? 'zip' : 'png'}`; document.body.appendChild(a); a.click(); document.body.removeChild(a); setTimeout(() => window.URL.revokeObjectURL(url), 60_000); } // Thin wrapper over `getSwatchStyle` from utils/colors so the modal's render // sites keep their existing call shape. Transparent (alpha=00) spools now // render as a checkerboard pattern instead of collapsing to solid black // (#1545). function swatchStyle(rgba: string | null | undefined): React.CSSProperties { return getSwatchStyle(rgba); } function labelColorName(s: SpoolForLabel): string | null { return resolveSpoolColorName(s.color_name, s.rgba, s.color_name_is_synthesized); } function spoolDisplayName(s: SpoolForLabel): string { // Resolved, not stored: most Bambu spools arrive with no colour name on the // tag, and picking a label template for "PLA Silk" tells you nothing about // which of six red spools you are looking at (#3090). const head = labelColorName(s) ?? `${s.material}${s.subtype ? ` ${s.subtype}` : ''}`; const brand = s.brand ? ` · ${s.brand}` : ''; return `${head}${brand}`; } /** Build a lowercased haystack that the search input matches against. */ function searchableText(s: SpoolForLabel): string { return [labelColorName(s), s.color_name, s.material, s.subtype, s.brand, `#${s.id}`] .filter(Boolean) .join(' ') .toLowerCase(); } type SortMode = 'id' | 'color'; /** Sort key for the "by colour" mode (#1410). * * Returns a 2-tuple so JS array compare does the right thing without us having * to spell out a comparator: ``[bucket, position]``. Chromatic colours * (saturation above the threshold) go in bucket 0 ordered by HSL hue, so the * sheet reads as a continuous rainbow. Achromatic colours (white / grey / * black, plus missing/invalid rgba) go in bucket 1 ordered by lightness so the * neutrals trail at the end of the rainbow going dark → light. Multi-colour * spools sort on their primary ``rgba``; their ``extra_colors`` stripe is * still rendered on the label itself but doesn't drive the sort. */ function colorSortKey(rgba: string | null | undefined): [number, number] { if (!rgba) return [1, 0]; // unknown colour — bucket with the neutrals at black const cleaned = rgba.replace(/^#/, '').slice(0, 6); if (cleaned.length !== 6) return [1, 0]; const r = parseInt(cleaned.slice(0, 2), 16); const g = parseInt(cleaned.slice(2, 4), 16); const b = parseInt(cleaned.slice(4, 6), 16); if ([r, g, b].some(Number.isNaN)) return [1, 0]; const rn = r / 255; const gn = g / 255; const bn = b / 255; const max = Math.max(rn, gn, bn); const min = Math.min(rn, gn, bn); const l = (max + min) / 2; const delta = max - min; // Saturation in the HSL definition. Achromatic cutoff at 0.1 is generous — // matches what feels "grey enough" to a user picking colours, without // sending dark muted colours like deep navy into the neutrals bucket. const s = delta === 0 ? 0 : delta / (1 - Math.abs(2 * l - 1)); if (s < 0.1) return [1, l]; // neutrals: ordered black → white let h = 0; if (max === rn) h = ((gn - bn) / delta) % 6; else if (max === gn) h = (bn - rn) / delta + 2; else h = (rn - gn) / delta + 4; h = h * 60; if (h < 0) h += 360; return [0, h]; // chromatic: ordered by hue 0..360 } export function LabelTemplatePickerModal({ isOpen, onClose, availableSpools, initialSelectedIds, spoolmanMode, }: LabelTemplatePickerModalProps) { const { t, i18n } = useTranslation(); // The spool filter below resolves colour names through the catalog; its // memo has to recompute when the catalog finishes loading (#3090). const colorCatalogVersion = useColorCatalogVersion(); const { showToast } = useToast(); const { hasPermission } = useAuth(); // Saving, editing and deleting templates is inventory:update, like storage // locations; anyone who can print can use them (#3296). const canManageTemplates = hasPermission('inventory:update'); const queryClient = useQueryClient(); const [pending, setPending] = useState(false); const [selectedIds, setSelectedIds] = useState>(new Set()); const [search, setSearch] = useState(''); const [materialFilter, setMaterialFilter] = useState(''); const [sortMode, setSortMode] = useState('id'); const [prefs, setPrefs] = useState(DEFAULT_PREFS); const [startingPositionInput, setStartingPositionInput] = useState('1'); const [previewUrl, setPreviewUrl] = useState(null); const [previewLoading, setPreviewLoading] = useState(false); const [previewError, setPreviewError] = useState(null); // The object URL on screen. Freed when its replacement arrives, not when the // options change, so the old label stays visible while the new one renders. const previewUrlRef = useRef(null); // A saved template being edited: its name and layout as typed, not yet saved. const [editing, setEditing] = useState<{ name: string; draft: LayoutDraft } | null>(null); // The name typed for "Save as template"; null while that form is closed. const [newTemplateName, setNewTemplateName] = useState(null); const [confirmDelete, setConfirmDelete] = useState(false); // When the dialog last opened: a remembered template is only given up on // when a list fetched since then lacks it, not a cached one (#3296 review). const openedAtRef = useRef(0); const savedQuery = useQuery({ queryKey: SAVED_TEMPLATES_KEY, queryFn: api.getLabelTemplates, enabled: isOpen, // Someone else may have saved or deleted one since the last open. staleTime: 0, }); const savedTemplates = useMemo(() => savedQuery.data ?? [], [savedQuery.data]); const saveMutation = useMutation({ mutationFn: ({ id, name, layout }: { id?: number; name: string; layout: LabelSheetLayout }) => id === undefined ? api.createLabelTemplate({ name, layout }) : api.updateLabelTemplate(id, { name, layout }), onSuccess: (saved) => { // In the list before it is selected, so the selection doesn't fall back. queryClient.setQueryData(SAVED_TEMPLATES_KEY, (old = []) => [ ...old.filter((tpl) => tpl.id !== saved.id), saved, ]); void queryClient.invalidateQueries({ queryKey: SAVED_TEMPLATES_KEY }); }, onError: (err) => { if (err instanceof ApiError && err.status === 409) { showToast(t('inventory.labels.custom.nameTaken', 'A label template with this name already exists.'), 'error'); return; } const msg = err instanceof Error ? err.message : String(err); showToast(t('inventory.labels.custom.saveFailed', 'Could not save the template: {{msg}}', { msg }), 'error'); }, }); const deleteMutation = useMutation({ mutationFn: (id: number) => api.deleteLabelTemplate(id), onSuccess: (_, id) => { queryClient.setQueryData(SAVED_TEMPLATES_KEY, (old = []) => old.filter((tpl) => tpl.id !== id), ); void queryClient.invalidateQueries({ queryKey: SAVED_TEMPLATES_KEY }); }, onError: (err) => { const msg = err instanceof Error ? err.message : String(err); showToast(t('inventory.labels.custom.deleteFailed', 'Could not delete the template: {{msg}}', { msg }), 'error'); }, }); // Sync from caller and reset transient state on open. Intentionally not // reactive to props while open — once the user starts editing we don't want // a parent re-render to clobber their selection / filter / search. The // label options come back as the user last left them. useEffect(() => { if (isOpen) { openedAtRef.current = Date.now(); const allowed = new Set(availableSpools.map((s) => s.id)); setSelectedIds(new Set(initialSelectedIds.filter((id) => allowed.has(id)))); setSearch(''); setMaterialFilter(''); setSortMode('id'); setPrefs(loadPrefs()); setStartingPositionInput('1'); setPending(false); setEditing(null); setNewTemplateName(null); setConfirmDelete(false); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [isOpen]); const sortedSpools = useMemo(() => { const copy = [...availableSpools]; if (sortMode === 'color') { copy.sort((a, b) => { const ka = colorSortKey(a.rgba); const kb = colorSortKey(b.rgba); if (ka[0] !== kb[0]) return ka[0] - kb[0]; if (ka[1] !== kb[1]) return ka[1] - kb[1]; // Stable tiebreaker on ID so identical colours print in a deterministic // order across renders. return a.id - b.id; }); return copy; } copy.sort((a, b) => a.id - b.id); return copy; }, [availableSpools, sortMode]); // Material chips are derived from the *full* available set so they stay // stable when search/material filter narrows the visible list. const materials = useMemo(() => { const set = new Set(); for (const s of sortedSpools) { if (s.material) set.add(s.material.toUpperCase()); } return [...set].sort(); }, [sortedSpools]); const visibleSpools = useMemo(() => { // Named so this memo depends on it: searchableText resolves colour names // through the catalog, which resolveSpoolColorName reads from module state // the linter cannot follow. Without it a query typed before the catalog // loads keeps its empty result (#3090). void colorCatalogVersion; const q = search.trim().toLowerCase(); return sortedSpools.filter((s) => { if (materialFilter && (s.material || '').toUpperCase() !== materialFilter) return false; if (q && !searchableText(s).includes(q)) return false; return true; }); }, [sortedSpools, search, materialFilter, colorCatalogVersion]); const allVisibleChecked = visibleSpools.length > 0 && visibleSpools.every((s) => selectedIds.has(s.id)); const template = prefs.template; const fields = fieldsFor(prefs, template); const fieldsKey = fields.join(','); // A saved template or a one-off custom sheet prints as "custom" with its // layout. The layout on screen is what prints, so an edit can be tried // before it is saved. const savedId = savedIdOf(template); const savedTemplate = savedId === null ? undefined : savedTemplates.find((tpl) => tpl.id === savedId); const isCustomSheet = template === 'custom' || savedId !== null; const activeDraft: LayoutDraft | null = template === 'custom' ? prefs.customDraft : editing ? editing.draft : savedTemplate ? draftFromLayout(savedTemplate.layout) : null; const problem = activeDraft ? layoutProblem(activeDraft) : null; const activeLayout = activeDraft && !problem ? parseDraft(activeDraft) : null; // Waiting for the saved list, or a layout that can't print: nothing to send. const sheetReady = !isCustomSheet || activeLayout !== null; const requestTemplate: SpoolLabelRequestTemplate = isCustomSheet ? 'custom' : (template as SpoolLabelTemplate); const layoutKey = activeLayout ? JSON.stringify(activeLayout) : ''; // A remembered saved template that has since been deleted: back to the // default, and out of any edit of it, which would otherwise still send its // layout with the built-in template (a 422). Only once a list fetched since // the dialog opened says so. const savedListIsFresh = savedQuery.isSuccess && !savedQuery.isFetching && savedQuery.dataUpdatedAt >= openedAtRef.current; useEffect(() => { if (!isOpen || !savedListIsFresh || savedId === null) return; if (savedTemplates.some((tpl) => tpl.id === savedId)) return; setEditing(null); setNewTemplateName(null); setConfirmDelete(false); setPrefs((prev) => { const next = { ...prev, template: DEFAULT_PREFS.template }; savePrefs(next); return next; }); }, [isOpen, savedListIsFresh, savedTemplates, savedId]); // The preview shows the first spool that will print, in print order. const previewSpoolId = sortedSpools.find((s) => selectedIds.has(s.id))?.id ?? null; function showPreview(url: string | null) { if (previewUrlRef.current) window.URL.revokeObjectURL(previewUrlRef.current); previewUrlRef.current = url; setPreviewUrl(url); } // Re-render the preview a moment after the last change, dropping any // request still in flight so a slow answer can't overwrite a newer one. useEffect(() => { if (!isOpen || previewSpoolId === null || !sheetReady) { showPreview(null); setPreviewError(null); setPreviewLoading(false); return; } const controller = new AbortController(); setPreviewLoading(true); const timer = window.setTimeout(async () => { const request = { spool_id: previewSpoolId, template: requestTemplate, ...(layoutKey ? { layout: JSON.parse(layoutKey) as LabelSheetLayout } : {}), monochrome: prefs.monochrome, fields: fieldsKey ? (fieldsKey.split(',') as SpoolLabelField[]) : [], }; try { const blob = spoolmanMode ? await api.previewSpoolmanSpoolLabel(request, controller.signal) : await api.previewSpoolLabel(request, controller.signal); if (controller.signal.aborted) return; showPreview(window.URL.createObjectURL(blob)); setPreviewError(null); } catch (err) { if (controller.signal.aborted) return; showPreview(null); setPreviewError(err instanceof Error ? err.message : String(err)); } finally { if (!controller.signal.aborted) setPreviewLoading(false); } }, 250); return () => { window.clearTimeout(timer); controller.abort(); }; }, [isOpen, previewSpoolId, sheetReady, requestTemplate, layoutKey, fieldsKey, prefs.monochrome, spoolmanMode]); // Free the last preview when the modal unmounts. useEffect( () => () => { if (previewUrlRef.current) window.URL.revokeObjectURL(previewUrlRef.current); }, [], ); if (!isOpen) return null; const selectedCount = selectedIds.size; const noSelection = selectedCount === 0; const sheetCapacity = isCustomSheet ? activeLayout ? activeLayout.cols * activeLayout.rows : undefined : SHEET_CAPACITIES[template as SpoolLabelTemplate]; const startingPosition = Number(startingPositionInput); const startingPositionIsValid = sheetCapacity === undefined || (Number.isInteger(startingPosition) && startingPosition >= 1 && startingPosition <= sheetCapacity); const templateOption = TEMPLATE_OPTIONS.find((o) => o.value === template) ?? TEMPLATE_OPTIONS[0]; // PNG of whole sheet pages is capped at pages × dpi, as on the server. const pngSheetPages = prefs.format === 'png' && sheetCapacity !== undefined && startingPositionIsValid ? sheetPageCount(sheetCapacity, selectedCount, startingPosition) : 0; const pngTooLarge = pngSheetPages * prefs.dpi > MAX_PNG_SHEET_PAGES_X_DPI; const canPrint = !noSelection && !pending && startingPositionIsValid && sheetReady && !pngTooLarge; function updatePrefs(change: Partial) { setPrefs((prev) => { const next = { ...prev, ...change }; savePrefs(next); return next; }); } function chooseTemplate(choice: TemplateChoice) { setEditing(null); setNewTemplateName(null); updatePrefs({ template: choice }); } function layoutSummary(layout: LabelSheetLayout): string { return t( 'inventory.labels.custom.summary', '{{page}} · {{width}} × {{height}} mm · {{capacity}} labels ({{cols}} × {{rows}})', { page: layout.page === 'a4' ? t('inventory.labels.custom.pageShortA4', 'A4') : t('inventory.labels.custom.pageShortLetter', 'Letter'), width: formatMm(layout.label_w_mm, i18n.language), height: formatMm(layout.label_h_mm, i18n.language), capacity: layout.cols * layout.rows, cols: layout.cols, rows: layout.rows, }, ); } function saveNewTemplate(name: string, layout: LabelSheetLayout) { // The new template keeps the lines chosen for the sheet it was made from, // as they are when the save completes: they can be ticked meanwhile. const source = template; saveMutation.mutate( { name: name.trim(), layout }, { onSuccess: (saved) => { setEditing(null); setNewTemplateName(null); const choice = savedChoice(saved.id); setPrefs((prev) => { const next = { ...prev, template: choice, fields: { ...prev.fields, [choice]: fieldsFor(prev, source) }, }; savePrefs(next); return next; }); showToast(t('inventory.labels.custom.saved', 'Template "{{name}}" saved', { name: saved.name }), 'success'); }, }, ); } function saveEditedTemplate(id: number, name: string, layout: LabelSheetLayout) { saveMutation.mutate( { id, name: name.trim(), layout }, { onSuccess: (saved) => { setEditing(null); showToast(t('inventory.labels.custom.saved', 'Template "{{name}}" saved', { name: saved.name }), 'success'); }, }, ); } function deleteSavedTemplate(tpl: SavedLabelTemplate) { deleteMutation.mutate(tpl.id, { onSuccess: () => { setConfirmDelete(false); setEditing(null); updatePrefs({ template: DEFAULT_PREFS.template }); showToast(t('inventory.labels.custom.deleted', 'Template "{{name}}" deleted', { name: tpl.name }), 'success'); }, }); } function setFields(next: SpoolLabelField[]) { // Stored in print order, so the saved list reads like the label. const ordered = SPOOL_LABEL_FIELDS.filter((f) => next.includes(f)); updatePrefs({ fields: { ...prefs.fields, [template]: ordered } }); } function toggleField(field: SpoolLabelField) { setFields(fields.includes(field) ? fields.filter((f) => f !== field) : [...fields, field]); } function toggleOne(id: number) { setSelectedIds((prev) => { const next = new Set(prev); if (next.has(id)) next.delete(id); else next.add(id); return next; }); } function selectAllVisible() { setSelectedIds((prev) => { const next = new Set(prev); for (const s of visibleSpools) next.add(s.id); return next; }); } function deselectVisible() { setSelectedIds((prev) => { const next = new Set(prev); for (const s of visibleSpools) next.delete(s.id); return next; }); } function clearAll() { setSelectedIds(new Set()); } async function handlePrint() { if (!canPrint) return; // Order matters: the backend (labels.py) prints labels in the same order // we send IDs. Use the sorted list so a "by colour" sort flows through to // the output instead of being clobbered by an ascending-ID re-sort. const ids = sortedSpools.filter((s) => selectedIds.has(s.id)).map((s) => s.id); const request = { spool_ids: ids, template: requestTemplate, ...(activeLayout ? { layout: activeLayout } : {}), monochrome: prefs.monochrome, starting_position: sheetCapacity === undefined ? 1 : startingPosition, fields, format: prefs.format, dpi: prefs.dpi, }; setPending(true); try { const blob = spoolmanMode ? await api.printSpoolmanSpoolLabels(request) : await api.printSpoolLabels(request); if (prefs.format === 'pdf') openBlobInNewTab(blob); else downloadBlob(blob, requestTemplate); onClose(); } catch (err) { const msg = err instanceof Error ? err.message : String(err); showToast( t('inventory.labels.error', 'Could not generate labels: {{msg}}', { msg }), 'error', ); } finally { setPending(false); } } const chipClass = (active: boolean) => `px-2 py-0.5 text-xs rounded-full border transition ${ active ? 'bg-bambu-green text-bambu-dark border-bambu-green' : 'bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray' }`; return (
{/* Header */}

{t('inventory.labels.title', 'Print spool labels')}

{selectedCount > 0 && ( ({t('inventory.labels.selectedCount', '{{count}} selected', { count: selectedCount })}) )}
{/* Two columns from md up: which spools on the left, what the label looks like on the right. Stacked and scrolled as one on phones. */}
{/* Search + material chips */}
setSearch(e.target.value)} placeholder={t('inventory.labels.searchPlaceholder', 'Search name, brand, or #ID')} className="w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray focus:outline-none focus:border-bambu-green" />
{materials.length > 1 && (
{t('inventory.labels.filterByMaterial', 'Material:')} {materials.map((m) => ( ))}
)}
{t('inventory.labels.sortBy.label')}
{/* Action bar */}
{t('inventory.labels.pickSpools', 'Pick which spools to print labels for:')}
{/* Spool list */}
{visibleSpools.length === 0 ? (
{sortedSpools.length === 0 ? t('inventory.labels.noSpoolsToShow', 'No spools to show. Adjust your filter and try again.') : t('inventory.labels.noMatches', 'No spools match the current search or filter.')}
) : (
    {visibleSpools.map((s) => { const checked = selectedIds.has(s.id); return (
  • ); })}
)}
{/* Label size */}

{template === 'custom' ? t('inventory.labels.custom.hint', 'Describe your own label sheet below.') : savedId !== null ? savedTemplate ? layoutSummary(savedTemplate.layout) : null : t(`inventory.labels.templates.${templateOption.i18nKey}.hint`, templateOption.fallbackHint)}

{/* A saved template: its sheet, and Edit / Delete for those who may (#3296). */} {savedTemplate && !editing && (
{canManageTemplates && (
)}
)} {/* Editing a saved template: the name and the whole layout. */} {savedTemplate && editing && (
setEditing({ ...editing, name })} /> setEditing({ ...editing, draft })} problem={problem} startingPosition={startingPositionIsValid ? startingPosition : 1} />
)} {/* A one-off custom sheet, and saving it under a name. */} {template === 'custom' && (
updatePrefs({ customDraft })} problem={problem} startingPosition={startingPositionIsValid ? startingPosition : 1} /> {canManageTemplates && (newTemplateName === null ? ( ) : (
))}
)} {/* Preview */}
{previewSpoolId === null ? t('inventory.labels.preview', 'Preview') : t('inventory.labels.previewOf', 'Preview of #{{id}}', { id: previewSpoolId })}
{previewSpoolId === null ? ( {t('inventory.labels.previewNoSelection', 'Select a spool to see its label.')} ) : !sheetReady ? ( {t('inventory.labels.custom.previewWaiting', 'The preview appears once the sheet layout is complete.')} ) : previewError ? ( {t('inventory.labels.previewError', 'Could not render the preview: {{msg}}', { msg: previewError })} ) : previewUrl ? ( {t('inventory.labels.previewAlt', ) : null} {previewLoading && ( )}

{t('inventory.labels.previewHint', 'Lines that don\'t fit on this label size are left out.')}

{/* Label content */}
{t('inventory.labels.content', 'Print on the label')}
{SPOOL_LABEL_FIELDS.map((field) => { const checked = fields.includes(field); const { i18nKey, fallback } = FIELD_LABELS[field]; return ( ); })}
{/* Print options */}
{sheetCapacity !== undefined && (
setStartingPositionInput(event.target.value)} aria-describedby="label-starting-position-help" className="w-20 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:border-bambu-green" />
{!startingPositionIsValid ? t( 'inventory.labels.startingPositionInvalid', 'Enter a whole number from 1 to {{capacity}}.', { capacity: sheetCapacity }, ) : startingPosition === 1 ? t('inventory.labels.startingPositionFirst', 'Printing starts at position 1.') : t( 'inventory.labels.startingPositionSkipped', 'Positions 1 through {{lastPosition}} will be left blank on the first sheet.', { lastPosition: startingPosition - 1 }, )}
)} {sheetCapacity !== undefined && (

{t( 'inventory.labels.scaleHint', 'Print sheets at 100% (actual size), not "Fit to page": a shrunk page drifts off the labels.', )}

)}
{t('inventory.labels.format', 'Output:')} {prefs.format === 'png' && ( )}
{prefs.format === 'png' && (

{t( 'inventory.labels.pngHint', 'For label printer software that takes images. Match your printer\'s resolution; several labels come as a ZIP.', )}

)} {pngTooLarge && (

{t( 'inventory.labels.pngTooLarge', 'PNG export is limited to {{maxPages}} sheet pages at {{dpi}} dpi, and this is {{pages}}. Use PDF, a lower resolution or fewer spools.', { maxPages: Math.floor(MAX_PNG_SHEET_PAGES_X_DPI / prefs.dpi), dpi: prefs.dpi, pages: pngSheetPages }, )}

)}
{confirmDelete && savedTemplate && ( deleteSavedTemplate(savedTemplate)} onCancel={() => setConfirmDelete(false)} /> )}
); } function TemplateNameInput({ value, onChange, autoFocus = false, }: { value: string; onChange: (name: string) => void; autoFocus?: boolean; }) { const { t } = useTranslation(); return ( ); }