LabelTemplatePickerModal.tsx 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363
  1. import { useEffect, useMemo, useRef, useState } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
  4. import { X, Loader2, Printer, CheckSquare, Square, Search, Download } from 'lucide-react';
  5. import {
  6. api,
  7. ApiError,
  8. DEFAULT_SPOOL_LABEL_FIELDS,
  9. SPOOL_LABEL_FIELDS,
  10. type LabelSheetLayout,
  11. type SavedLabelTemplate,
  12. type SpoolLabelField,
  13. type SpoolLabelRequestTemplate,
  14. type SpoolLabelTemplate,
  15. type InventorySpool,
  16. } from '../api/client';
  17. import { Button } from './Button';
  18. import { ConfirmModal } from './ConfirmModal';
  19. import { LabelSheetDiagram, LabelSheetLayoutEditor } from './LabelSheetLayoutEditor';
  20. import { useAuth } from '../contexts/AuthContext';
  21. import { useToast } from '../contexts/ToastContext';
  22. import {
  23. DEFAULT_LAYOUT,
  24. MAX_PNG_SHEET_PAGES_X_DPI,
  25. draftFromLayout,
  26. formatMm,
  27. isLayoutDraft,
  28. layoutProblem,
  29. parseDraft,
  30. sheetPageCount,
  31. type LayoutDraft,
  32. } from '../utils/labelSheetLayout';
  33. import { getSwatchStyle, resolveSpoolColorName } from '../utils/colors';
  34. import { useColorCatalogVersion } from '../hooks/useColorCatalogVersion';
  35. /** Subset of InventorySpool the modal needs for checkbox rendering. */
  36. type SpoolForLabel = Pick<
  37. InventorySpool,
  38. 'id' | 'material' | 'subtype' | 'brand' | 'color_name' | 'color_name_is_synthesized' | 'rgba'
  39. >;
  40. interface LabelTemplatePickerModalProps {
  41. isOpen: boolean;
  42. onClose: () => void;
  43. /** All spools the modal can choose from. Typically the page's current
  44. * filter result so the modal stays consistent with what the user sees. */
  45. availableSpools: SpoolForLabel[];
  46. /** IDs to pre-check when the modal opens. Per-card icon passes a single ID;
  47. * the bulk header button passes every visible ID so the user lands in
  48. * "all checked" and refines downward. */
  49. initialSelectedIds: number[];
  50. spoolmanMode: boolean;
  51. }
  52. interface TemplateOption {
  53. value: SpoolLabelTemplate;
  54. i18nKey: string;
  55. fallbackLabel: string;
  56. fallbackHint: string;
  57. }
  58. const TEMPLATE_OPTIONS: TemplateOption[] = [
  59. {
  60. value: 'ams_holder_74x33',
  61. i18nKey: 'amsHolderSmall',
  62. fallbackLabel: 'AMS holder — small (74 × 33 mm)',
  63. fallbackHint: 'Single label per page; matches the printable label from MakerWorld model 752566 (AMS Filament Label Holder).',
  64. },
  65. {
  66. value: 'ams_holder_75x55',
  67. i18nKey: 'amsHolderLarge',
  68. fallbackLabel: 'AMS holder — large (75 × 55 mm)',
  69. 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.',
  70. },
  71. {
  72. value: 'box_40x30',
  73. i18nKey: 'box40x30',
  74. fallbackLabel: 'Box label (40 × 30 mm)',
  75. fallbackHint: 'Single label per page; common DK/Brother roll size, good for filament-bag and storage-bin labels.',
  76. },
  77. {
  78. value: 'box_62x29',
  79. i18nKey: 'box',
  80. fallbackLabel: 'Box label (62 × 29 mm)',
  81. fallbackHint: 'Single label per page; sized for Brother PT/QL and Dymo small labels.',
  82. },
  83. {
  84. value: 'avery_l7160',
  85. i18nKey: 'averyL7160',
  86. fallbackLabel: 'Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)',
  87. fallbackHint: 'EU sheet stock; 21 labels per A4 page.',
  88. },
  89. {
  90. value: 'avery_5160',
  91. i18nKey: 'avery5160',
  92. fallbackLabel: 'Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)',
  93. fallbackHint: 'US sheet stock; 30 labels per Letter page.',
  94. },
  95. ];
  96. const SHEET_CAPACITIES: Partial<Record<SpoolLabelTemplate, number>> = {
  97. avery_l7160: 21,
  98. avery_5160: 30,
  99. };
  100. type OutputFormat = 'pdf' | 'png';
  101. type PngDpi = 203 | 300 | 600;
  102. const PNG_DPIS: PngDpi[] = [203, 300, 600];
  103. // What the checkboxes read, keyed by SpoolLabelField (#2981).
  104. const FIELD_LABELS: Record<SpoolLabelField, { i18nKey: string; fallback: string }> = {
  105. brand: { i18nKey: 'brand', fallback: 'Brand' },
  106. material: { i18nKey: 'material', fallback: 'Material and subtype' },
  107. hex: { i18nKey: 'hex', fallback: 'Colour code' },
  108. name: { i18nKey: 'name', fallback: 'Colour or filament name' },
  109. location: { i18nKey: 'location', fallback: 'Storage location' },
  110. material_number: { i18nKey: 'materialNumber', fallback: 'Material number' },
  111. temps: { i18nKey: 'temps', fallback: 'Nozzle temperature' },
  112. weight: { i18nKey: 'weight', fallback: 'Net weight' },
  113. note: { i18nKey: 'note', fallback: 'Note' },
  114. added: { i18nKey: 'added', fallback: 'Date added' },
  115. qr: { i18nKey: 'qr', fallback: 'QR code' },
  116. spool_id: { i18nKey: 'spoolId', fallback: 'Spool ID' },
  117. };
  118. // Remembered per browser. Printing only needs inventory access, and a server
  119. // setting would need settings access to save.
  120. const PREFS_STORAGE_KEY = 'bambuddy-label-print-options';
  121. // What the label size dropdown holds: a built-in template, a one-off custom
  122. // sheet, or a saved template by id (#3296).
  123. type TemplateChoice = SpoolLabelTemplate | 'custom' | `saved:${number}`;
  124. const SAVED_TEMPLATES_KEY = ['labelTemplates'];
  125. function savedChoice(id: number): TemplateChoice {
  126. return `saved:${id}`;
  127. }
  128. function savedIdOf(choice: TemplateChoice): number | null {
  129. return choice.startsWith('saved:') ? Number(choice.slice('saved:'.length)) : null;
  130. }
  131. function isTemplateChoice(value: unknown): value is TemplateChoice {
  132. if (typeof value !== 'string') return false;
  133. if (value === 'custom' || /^saved:[1-9]\d*$/.test(value)) return true;
  134. return TEMPLATE_OPTIONS.some((o) => o.value === value);
  135. }
  136. interface LabelPrefs {
  137. template: TemplateChoice;
  138. /** Chosen lines per template: a 40 × 30 roll and an A4 sheet fit different amounts. */
  139. fields: Partial<Record<TemplateChoice, SpoolLabelField[]>>;
  140. /** The one-off custom sheet, as last typed. */
  141. customDraft: LayoutDraft;
  142. monochrome: boolean;
  143. format: OutputFormat;
  144. dpi: PngDpi;
  145. }
  146. const DEFAULT_PREFS: LabelPrefs = {
  147. template: TEMPLATE_OPTIONS[0].value,
  148. fields: {},
  149. customDraft: draftFromLayout(DEFAULT_LAYOUT),
  150. monochrome: false,
  151. format: 'pdf',
  152. dpi: 300,
  153. };
  154. function loadPrefs(): LabelPrefs {
  155. let raw: unknown;
  156. try {
  157. raw = JSON.parse(localStorage.getItem(PREFS_STORAGE_KEY) ?? 'null');
  158. } catch {
  159. return DEFAULT_PREFS;
  160. }
  161. if (!raw || typeof raw !== 'object') return DEFAULT_PREFS;
  162. const r = raw as Partial<Record<keyof LabelPrefs, unknown>>;
  163. const fields: LabelPrefs['fields'] = {};
  164. if (r.fields && typeof r.fields === 'object') {
  165. for (const [tpl, list] of Object.entries(r.fields as Record<string, unknown>)) {
  166. if (!isTemplateChoice(tpl) || !Array.isArray(list)) continue;
  167. fields[tpl] = list.filter((f): f is SpoolLabelField =>
  168. (SPOOL_LABEL_FIELDS as readonly string[]).includes(f),
  169. );
  170. }
  171. }
  172. return {
  173. template: isTemplateChoice(r.template) ? r.template : DEFAULT_PREFS.template,
  174. fields,
  175. customDraft: isLayoutDraft(r.customDraft) ? r.customDraft : DEFAULT_PREFS.customDraft,
  176. monochrome: r.monochrome === true,
  177. format: r.format === 'png' ? 'png' : 'pdf',
  178. dpi: PNG_DPIS.includes(r.dpi as PngDpi) ? (r.dpi as PngDpi) : DEFAULT_PREFS.dpi,
  179. };
  180. }
  181. function savePrefs(prefs: LabelPrefs): void {
  182. try {
  183. localStorage.setItem(PREFS_STORAGE_KEY, JSON.stringify(prefs));
  184. } catch {
  185. // Private mode or storage disabled: the options just aren't remembered.
  186. }
  187. }
  188. function fieldsFor(prefs: LabelPrefs, template: TemplateChoice): SpoolLabelField[] {
  189. return prefs.fields[template] ?? DEFAULT_SPOOL_LABEL_FIELDS;
  190. }
  191. function openBlobInNewTab(blob: Blob): void {
  192. const url = window.URL.createObjectURL(blob);
  193. // Do NOT pass `noopener,noreferrer`: per the WindowFeatures spec, `noopener`
  194. // forces window.open to return `null` even on success, which made the
  195. // `if (!win)` popup-block fallback below fire on EVERY click — so the blob
  196. // tab opened (downloading a random-named PDF on systems without an inline
  197. // viewer) AND the `<a download>` fallback fired (downloading a second copy
  198. // named bambuddy-labels.pdf). Two identical PDFs per click — issue #1628.
  199. // The blob is same-origin, the destination is a passive PDF tab with no
  200. // script context, and `noreferrer` is a no-op for blob URLs, so dropping
  201. // these flags has no security impact.
  202. const win = window.open(url, '_blank');
  203. if (!win) {
  204. const a = document.createElement('a');
  205. a.href = url;
  206. a.download = 'bambuddy-labels.pdf';
  207. document.body.appendChild(a);
  208. a.click();
  209. document.body.removeChild(a);
  210. }
  211. setTimeout(() => window.URL.revokeObjectURL(url), 60_000);
  212. }
  213. /** Save a PNG, or a ZIP of PNGs when there were several pages. */
  214. function downloadBlob(blob: Blob, template: SpoolLabelRequestTemplate): void {
  215. const url = window.URL.createObjectURL(blob);
  216. const a = document.createElement('a');
  217. a.href = url;
  218. a.download = `bambuddy-labels-${template}.${blob.type === 'application/zip' ? 'zip' : 'png'}`;
  219. document.body.appendChild(a);
  220. a.click();
  221. document.body.removeChild(a);
  222. setTimeout(() => window.URL.revokeObjectURL(url), 60_000);
  223. }
  224. // Thin wrapper over `getSwatchStyle` from utils/colors so the modal's render
  225. // sites keep their existing call shape. Transparent (alpha=00) spools now
  226. // render as a checkerboard pattern instead of collapsing to solid black
  227. // (#1545).
  228. function swatchStyle(rgba: string | null | undefined): React.CSSProperties {
  229. return getSwatchStyle(rgba);
  230. }
  231. function labelColorName(s: SpoolForLabel): string | null {
  232. return resolveSpoolColorName(s.color_name, s.rgba, s.color_name_is_synthesized);
  233. }
  234. function spoolDisplayName(s: SpoolForLabel): string {
  235. // Resolved, not stored: most Bambu spools arrive with no colour name on the
  236. // tag, and picking a label template for "PLA Silk" tells you nothing about
  237. // which of six red spools you are looking at (#3090).
  238. const head = labelColorName(s) ?? `${s.material}${s.subtype ? ` ${s.subtype}` : ''}`;
  239. const brand = s.brand ? ` · ${s.brand}` : '';
  240. return `${head}${brand}`;
  241. }
  242. /** Build a lowercased haystack that the search input matches against. */
  243. function searchableText(s: SpoolForLabel): string {
  244. return [labelColorName(s), s.color_name, s.material, s.subtype, s.brand, `#${s.id}`]
  245. .filter(Boolean)
  246. .join(' ')
  247. .toLowerCase();
  248. }
  249. type SortMode = 'id' | 'color';
  250. /** Sort key for the "by colour" mode (#1410).
  251. *
  252. * Returns a 2-tuple so JS array compare does the right thing without us having
  253. * to spell out a comparator: ``[bucket, position]``. Chromatic colours
  254. * (saturation above the threshold) go in bucket 0 ordered by HSL hue, so the
  255. * sheet reads as a continuous rainbow. Achromatic colours (white / grey /
  256. * black, plus missing/invalid rgba) go in bucket 1 ordered by lightness so the
  257. * neutrals trail at the end of the rainbow going dark → light. Multi-colour
  258. * spools sort on their primary ``rgba``; their ``extra_colors`` stripe is
  259. * still rendered on the label itself but doesn't drive the sort.
  260. */
  261. function colorSortKey(rgba: string | null | undefined): [number, number] {
  262. if (!rgba) return [1, 0]; // unknown colour — bucket with the neutrals at black
  263. const cleaned = rgba.replace(/^#/, '').slice(0, 6);
  264. if (cleaned.length !== 6) return [1, 0];
  265. const r = parseInt(cleaned.slice(0, 2), 16);
  266. const g = parseInt(cleaned.slice(2, 4), 16);
  267. const b = parseInt(cleaned.slice(4, 6), 16);
  268. if ([r, g, b].some(Number.isNaN)) return [1, 0];
  269. const rn = r / 255;
  270. const gn = g / 255;
  271. const bn = b / 255;
  272. const max = Math.max(rn, gn, bn);
  273. const min = Math.min(rn, gn, bn);
  274. const l = (max + min) / 2;
  275. const delta = max - min;
  276. // Saturation in the HSL definition. Achromatic cutoff at 0.1 is generous —
  277. // matches what feels "grey enough" to a user picking colours, without
  278. // sending dark muted colours like deep navy into the neutrals bucket.
  279. const s = delta === 0 ? 0 : delta / (1 - Math.abs(2 * l - 1));
  280. if (s < 0.1) return [1, l]; // neutrals: ordered black → white
  281. let h = 0;
  282. if (max === rn) h = ((gn - bn) / delta) % 6;
  283. else if (max === gn) h = (bn - rn) / delta + 2;
  284. else h = (rn - gn) / delta + 4;
  285. h = h * 60;
  286. if (h < 0) h += 360;
  287. return [0, h]; // chromatic: ordered by hue 0..360
  288. }
  289. export function LabelTemplatePickerModal({
  290. isOpen,
  291. onClose,
  292. availableSpools,
  293. initialSelectedIds,
  294. spoolmanMode,
  295. }: LabelTemplatePickerModalProps) {
  296. const { t, i18n } = useTranslation();
  297. // The spool filter below resolves colour names through the catalog; its
  298. // memo has to recompute when the catalog finishes loading (#3090).
  299. const colorCatalogVersion = useColorCatalogVersion();
  300. const { showToast } = useToast();
  301. const { hasPermission } = useAuth();
  302. // Saving, editing and deleting templates is inventory:update, like storage
  303. // locations; anyone who can print can use them (#3296).
  304. const canManageTemplates = hasPermission('inventory:update');
  305. const queryClient = useQueryClient();
  306. const [pending, setPending] = useState(false);
  307. const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set());
  308. const [search, setSearch] = useState('');
  309. const [materialFilter, setMaterialFilter] = useState<string>('');
  310. const [sortMode, setSortMode] = useState<SortMode>('id');
  311. const [prefs, setPrefs] = useState<LabelPrefs>(DEFAULT_PREFS);
  312. const [startingPositionInput, setStartingPositionInput] = useState('1');
  313. const [previewUrl, setPreviewUrl] = useState<string | null>(null);
  314. const [previewLoading, setPreviewLoading] = useState(false);
  315. const [previewError, setPreviewError] = useState<string | null>(null);
  316. // The object URL on screen. Freed when its replacement arrives, not when the
  317. // options change, so the old label stays visible while the new one renders.
  318. const previewUrlRef = useRef<string | null>(null);
  319. // A saved template being edited: its name and layout as typed, not yet saved.
  320. const [editing, setEditing] = useState<{ name: string; draft: LayoutDraft } | null>(null);
  321. // The name typed for "Save as template"; null while that form is closed.
  322. const [newTemplateName, setNewTemplateName] = useState<string | null>(null);
  323. const [confirmDelete, setConfirmDelete] = useState(false);
  324. // When the dialog last opened: a remembered template is only given up on
  325. // when a list fetched since then lacks it, not a cached one (#3296 review).
  326. const openedAtRef = useRef(0);
  327. const savedQuery = useQuery({
  328. queryKey: SAVED_TEMPLATES_KEY,
  329. queryFn: api.getLabelTemplates,
  330. enabled: isOpen,
  331. // Someone else may have saved or deleted one since the last open.
  332. staleTime: 0,
  333. });
  334. const savedTemplates = useMemo(() => savedQuery.data ?? [], [savedQuery.data]);
  335. const saveMutation = useMutation({
  336. mutationFn: ({ id, name, layout }: { id?: number; name: string; layout: LabelSheetLayout }) =>
  337. id === undefined ? api.createLabelTemplate({ name, layout }) : api.updateLabelTemplate(id, { name, layout }),
  338. onSuccess: (saved) => {
  339. // In the list before it is selected, so the selection doesn't fall back.
  340. queryClient.setQueryData<SavedLabelTemplate[]>(SAVED_TEMPLATES_KEY, (old = []) => [
  341. ...old.filter((tpl) => tpl.id !== saved.id),
  342. saved,
  343. ]);
  344. void queryClient.invalidateQueries({ queryKey: SAVED_TEMPLATES_KEY });
  345. },
  346. onError: (err) => {
  347. if (err instanceof ApiError && err.status === 409) {
  348. showToast(t('inventory.labels.custom.nameTaken', 'A label template with this name already exists.'), 'error');
  349. return;
  350. }
  351. const msg = err instanceof Error ? err.message : String(err);
  352. showToast(t('inventory.labels.custom.saveFailed', 'Could not save the template: {{msg}}', { msg }), 'error');
  353. },
  354. });
  355. const deleteMutation = useMutation({
  356. mutationFn: (id: number) => api.deleteLabelTemplate(id),
  357. onSuccess: (_, id) => {
  358. queryClient.setQueryData<SavedLabelTemplate[]>(SAVED_TEMPLATES_KEY, (old = []) =>
  359. old.filter((tpl) => tpl.id !== id),
  360. );
  361. void queryClient.invalidateQueries({ queryKey: SAVED_TEMPLATES_KEY });
  362. },
  363. onError: (err) => {
  364. const msg = err instanceof Error ? err.message : String(err);
  365. showToast(t('inventory.labels.custom.deleteFailed', 'Could not delete the template: {{msg}}', { msg }), 'error');
  366. },
  367. });
  368. // Sync from caller and reset transient state on open. Intentionally not
  369. // reactive to props while open — once the user starts editing we don't want
  370. // a parent re-render to clobber their selection / filter / search. The
  371. // label options come back as the user last left them.
  372. useEffect(() => {
  373. if (isOpen) {
  374. openedAtRef.current = Date.now();
  375. const allowed = new Set(availableSpools.map((s) => s.id));
  376. setSelectedIds(new Set(initialSelectedIds.filter((id) => allowed.has(id))));
  377. setSearch('');
  378. setMaterialFilter('');
  379. setSortMode('id');
  380. setPrefs(loadPrefs());
  381. setStartingPositionInput('1');
  382. setPending(false);
  383. setEditing(null);
  384. setNewTemplateName(null);
  385. setConfirmDelete(false);
  386. }
  387. // eslint-disable-next-line react-hooks/exhaustive-deps
  388. }, [isOpen]);
  389. const sortedSpools = useMemo(() => {
  390. const copy = [...availableSpools];
  391. if (sortMode === 'color') {
  392. copy.sort((a, b) => {
  393. const ka = colorSortKey(a.rgba);
  394. const kb = colorSortKey(b.rgba);
  395. if (ka[0] !== kb[0]) return ka[0] - kb[0];
  396. if (ka[1] !== kb[1]) return ka[1] - kb[1];
  397. // Stable tiebreaker on ID so identical colours print in a deterministic
  398. // order across renders.
  399. return a.id - b.id;
  400. });
  401. return copy;
  402. }
  403. copy.sort((a, b) => a.id - b.id);
  404. return copy;
  405. }, [availableSpools, sortMode]);
  406. // Material chips are derived from the *full* available set so they stay
  407. // stable when search/material filter narrows the visible list.
  408. const materials = useMemo(() => {
  409. const set = new Set<string>();
  410. for (const s of sortedSpools) {
  411. if (s.material) set.add(s.material.toUpperCase());
  412. }
  413. return [...set].sort();
  414. }, [sortedSpools]);
  415. const visibleSpools = useMemo(() => {
  416. // Named so this memo depends on it: searchableText resolves colour names
  417. // through the catalog, which resolveSpoolColorName reads from module state
  418. // the linter cannot follow. Without it a query typed before the catalog
  419. // loads keeps its empty result (#3090).
  420. void colorCatalogVersion;
  421. const q = search.trim().toLowerCase();
  422. return sortedSpools.filter((s) => {
  423. if (materialFilter && (s.material || '').toUpperCase() !== materialFilter) return false;
  424. if (q && !searchableText(s).includes(q)) return false;
  425. return true;
  426. });
  427. }, [sortedSpools, search, materialFilter, colorCatalogVersion]);
  428. const allVisibleChecked =
  429. visibleSpools.length > 0 && visibleSpools.every((s) => selectedIds.has(s.id));
  430. const template = prefs.template;
  431. const fields = fieldsFor(prefs, template);
  432. const fieldsKey = fields.join(',');
  433. // A saved template or a one-off custom sheet prints as "custom" with its
  434. // layout. The layout on screen is what prints, so an edit can be tried
  435. // before it is saved.
  436. const savedId = savedIdOf(template);
  437. const savedTemplate = savedId === null ? undefined : savedTemplates.find((tpl) => tpl.id === savedId);
  438. const isCustomSheet = template === 'custom' || savedId !== null;
  439. const activeDraft: LayoutDraft | null =
  440. template === 'custom'
  441. ? prefs.customDraft
  442. : editing
  443. ? editing.draft
  444. : savedTemplate
  445. ? draftFromLayout(savedTemplate.layout)
  446. : null;
  447. const problem = activeDraft ? layoutProblem(activeDraft) : null;
  448. const activeLayout = activeDraft && !problem ? parseDraft(activeDraft) : null;
  449. // Waiting for the saved list, or a layout that can't print: nothing to send.
  450. const sheetReady = !isCustomSheet || activeLayout !== null;
  451. const requestTemplate: SpoolLabelRequestTemplate = isCustomSheet ? 'custom' : (template as SpoolLabelTemplate);
  452. const layoutKey = activeLayout ? JSON.stringify(activeLayout) : '';
  453. // A remembered saved template that has since been deleted: back to the
  454. // default, and out of any edit of it, which would otherwise still send its
  455. // layout with the built-in template (a 422). Only once a list fetched since
  456. // the dialog opened says so.
  457. const savedListIsFresh =
  458. savedQuery.isSuccess && !savedQuery.isFetching && savedQuery.dataUpdatedAt >= openedAtRef.current;
  459. useEffect(() => {
  460. if (!isOpen || !savedListIsFresh || savedId === null) return;
  461. if (savedTemplates.some((tpl) => tpl.id === savedId)) return;
  462. setEditing(null);
  463. setNewTemplateName(null);
  464. setConfirmDelete(false);
  465. setPrefs((prev) => {
  466. const next = { ...prev, template: DEFAULT_PREFS.template };
  467. savePrefs(next);
  468. return next;
  469. });
  470. }, [isOpen, savedListIsFresh, savedTemplates, savedId]);
  471. // The preview shows the first spool that will print, in print order.
  472. const previewSpoolId = sortedSpools.find((s) => selectedIds.has(s.id))?.id ?? null;
  473. function showPreview(url: string | null) {
  474. if (previewUrlRef.current) window.URL.revokeObjectURL(previewUrlRef.current);
  475. previewUrlRef.current = url;
  476. setPreviewUrl(url);
  477. }
  478. // Re-render the preview a moment after the last change, dropping any
  479. // request still in flight so a slow answer can't overwrite a newer one.
  480. useEffect(() => {
  481. if (!isOpen || previewSpoolId === null || !sheetReady) {
  482. showPreview(null);
  483. setPreviewError(null);
  484. setPreviewLoading(false);
  485. return;
  486. }
  487. const controller = new AbortController();
  488. setPreviewLoading(true);
  489. const timer = window.setTimeout(async () => {
  490. const request = {
  491. spool_id: previewSpoolId,
  492. template: requestTemplate,
  493. ...(layoutKey ? { layout: JSON.parse(layoutKey) as LabelSheetLayout } : {}),
  494. monochrome: prefs.monochrome,
  495. fields: fieldsKey ? (fieldsKey.split(',') as SpoolLabelField[]) : [],
  496. };
  497. try {
  498. const blob = spoolmanMode
  499. ? await api.previewSpoolmanSpoolLabel(request, controller.signal)
  500. : await api.previewSpoolLabel(request, controller.signal);
  501. if (controller.signal.aborted) return;
  502. showPreview(window.URL.createObjectURL(blob));
  503. setPreviewError(null);
  504. } catch (err) {
  505. if (controller.signal.aborted) return;
  506. showPreview(null);
  507. setPreviewError(err instanceof Error ? err.message : String(err));
  508. } finally {
  509. if (!controller.signal.aborted) setPreviewLoading(false);
  510. }
  511. }, 250);
  512. return () => {
  513. window.clearTimeout(timer);
  514. controller.abort();
  515. };
  516. }, [isOpen, previewSpoolId, sheetReady, requestTemplate, layoutKey, fieldsKey, prefs.monochrome, spoolmanMode]);
  517. // Free the last preview when the modal unmounts.
  518. useEffect(
  519. () => () => {
  520. if (previewUrlRef.current) window.URL.revokeObjectURL(previewUrlRef.current);
  521. },
  522. [],
  523. );
  524. if (!isOpen) return null;
  525. const selectedCount = selectedIds.size;
  526. const noSelection = selectedCount === 0;
  527. const sheetCapacity = isCustomSheet
  528. ? activeLayout
  529. ? activeLayout.cols * activeLayout.rows
  530. : undefined
  531. : SHEET_CAPACITIES[template as SpoolLabelTemplate];
  532. const startingPosition = Number(startingPositionInput);
  533. const startingPositionIsValid =
  534. sheetCapacity === undefined ||
  535. (Number.isInteger(startingPosition) && startingPosition >= 1 && startingPosition <= sheetCapacity);
  536. const templateOption = TEMPLATE_OPTIONS.find((o) => o.value === template) ?? TEMPLATE_OPTIONS[0];
  537. // PNG of whole sheet pages is capped at pages × dpi, as on the server.
  538. const pngSheetPages =
  539. prefs.format === 'png' && sheetCapacity !== undefined && startingPositionIsValid
  540. ? sheetPageCount(sheetCapacity, selectedCount, startingPosition)
  541. : 0;
  542. const pngTooLarge = pngSheetPages * prefs.dpi > MAX_PNG_SHEET_PAGES_X_DPI;
  543. const canPrint = !noSelection && !pending && startingPositionIsValid && sheetReady && !pngTooLarge;
  544. function updatePrefs(change: Partial<LabelPrefs>) {
  545. setPrefs((prev) => {
  546. const next = { ...prev, ...change };
  547. savePrefs(next);
  548. return next;
  549. });
  550. }
  551. function chooseTemplate(choice: TemplateChoice) {
  552. setEditing(null);
  553. setNewTemplateName(null);
  554. updatePrefs({ template: choice });
  555. }
  556. function layoutSummary(layout: LabelSheetLayout): string {
  557. return t(
  558. 'inventory.labels.custom.summary',
  559. '{{page}} · {{width}} × {{height}} mm · {{capacity}} labels ({{cols}} × {{rows}})',
  560. {
  561. page:
  562. layout.page === 'a4'
  563. ? t('inventory.labels.custom.pageShortA4', 'A4')
  564. : t('inventory.labels.custom.pageShortLetter', 'Letter'),
  565. width: formatMm(layout.label_w_mm, i18n.language),
  566. height: formatMm(layout.label_h_mm, i18n.language),
  567. capacity: layout.cols * layout.rows,
  568. cols: layout.cols,
  569. rows: layout.rows,
  570. },
  571. );
  572. }
  573. function saveNewTemplate(name: string, layout: LabelSheetLayout) {
  574. // The new template keeps the lines chosen for the sheet it was made from,
  575. // as they are when the save completes: they can be ticked meanwhile.
  576. const source = template;
  577. saveMutation.mutate(
  578. { name: name.trim(), layout },
  579. {
  580. onSuccess: (saved) => {
  581. setEditing(null);
  582. setNewTemplateName(null);
  583. const choice = savedChoice(saved.id);
  584. setPrefs((prev) => {
  585. const next = {
  586. ...prev,
  587. template: choice,
  588. fields: { ...prev.fields, [choice]: fieldsFor(prev, source) },
  589. };
  590. savePrefs(next);
  591. return next;
  592. });
  593. showToast(t('inventory.labels.custom.saved', 'Template "{{name}}" saved', { name: saved.name }), 'success');
  594. },
  595. },
  596. );
  597. }
  598. function saveEditedTemplate(id: number, name: string, layout: LabelSheetLayout) {
  599. saveMutation.mutate(
  600. { id, name: name.trim(), layout },
  601. {
  602. onSuccess: (saved) => {
  603. setEditing(null);
  604. showToast(t('inventory.labels.custom.saved', 'Template "{{name}}" saved', { name: saved.name }), 'success');
  605. },
  606. },
  607. );
  608. }
  609. function deleteSavedTemplate(tpl: SavedLabelTemplate) {
  610. deleteMutation.mutate(tpl.id, {
  611. onSuccess: () => {
  612. setConfirmDelete(false);
  613. setEditing(null);
  614. updatePrefs({ template: DEFAULT_PREFS.template });
  615. showToast(t('inventory.labels.custom.deleted', 'Template "{{name}}" deleted', { name: tpl.name }), 'success');
  616. },
  617. });
  618. }
  619. function setFields(next: SpoolLabelField[]) {
  620. // Stored in print order, so the saved list reads like the label.
  621. const ordered = SPOOL_LABEL_FIELDS.filter((f) => next.includes(f));
  622. updatePrefs({ fields: { ...prefs.fields, [template]: ordered } });
  623. }
  624. function toggleField(field: SpoolLabelField) {
  625. setFields(fields.includes(field) ? fields.filter((f) => f !== field) : [...fields, field]);
  626. }
  627. function toggleOne(id: number) {
  628. setSelectedIds((prev) => {
  629. const next = new Set(prev);
  630. if (next.has(id)) next.delete(id);
  631. else next.add(id);
  632. return next;
  633. });
  634. }
  635. function selectAllVisible() {
  636. setSelectedIds((prev) => {
  637. const next = new Set(prev);
  638. for (const s of visibleSpools) next.add(s.id);
  639. return next;
  640. });
  641. }
  642. function deselectVisible() {
  643. setSelectedIds((prev) => {
  644. const next = new Set(prev);
  645. for (const s of visibleSpools) next.delete(s.id);
  646. return next;
  647. });
  648. }
  649. function clearAll() {
  650. setSelectedIds(new Set());
  651. }
  652. async function handlePrint() {
  653. if (!canPrint) return;
  654. // Order matters: the backend (labels.py) prints labels in the same order
  655. // we send IDs. Use the sorted list so a "by colour" sort flows through to
  656. // the output instead of being clobbered by an ascending-ID re-sort.
  657. const ids = sortedSpools.filter((s) => selectedIds.has(s.id)).map((s) => s.id);
  658. const request = {
  659. spool_ids: ids,
  660. template: requestTemplate,
  661. ...(activeLayout ? { layout: activeLayout } : {}),
  662. monochrome: prefs.monochrome,
  663. starting_position: sheetCapacity === undefined ? 1 : startingPosition,
  664. fields,
  665. format: prefs.format,
  666. dpi: prefs.dpi,
  667. };
  668. setPending(true);
  669. try {
  670. const blob = spoolmanMode
  671. ? await api.printSpoolmanSpoolLabels(request)
  672. : await api.printSpoolLabels(request);
  673. if (prefs.format === 'pdf') openBlobInNewTab(blob);
  674. else downloadBlob(blob, requestTemplate);
  675. onClose();
  676. } catch (err) {
  677. const msg = err instanceof Error ? err.message : String(err);
  678. showToast(
  679. t('inventory.labels.error', 'Could not generate labels: {{msg}}', { msg }),
  680. 'error',
  681. );
  682. } finally {
  683. setPending(false);
  684. }
  685. }
  686. const chipClass = (active: boolean) =>
  687. `px-2 py-0.5 text-xs rounded-full border transition ${
  688. active
  689. ? 'bg-bambu-green text-bambu-dark border-bambu-green'
  690. : 'bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray'
  691. }`;
  692. return (
  693. <div className="fixed inset-0 z-50 flex items-start sm:items-center justify-center p-4 overflow-y-auto">
  694. <div
  695. className="absolute inset-0 bg-black/60 backdrop-blur-sm"
  696. onClick={onClose}
  697. />
  698. <div
  699. data-testid="label-template-picker-panel"
  700. className="relative w-full max-w-5xl bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] overflow-clip flex flex-col my-auto"
  701. >
  702. {/* Header */}
  703. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  704. <div className="flex items-center gap-2">
  705. <Printer className="w-5 h-5 text-bambu-green" />
  706. <h2 className="text-lg font-semibold text-white">
  707. {t('inventory.labels.title', 'Print spool labels')}
  708. </h2>
  709. {selectedCount > 0 && (
  710. <span className="text-sm text-bambu-gray">
  711. ({t('inventory.labels.selectedCount', '{{count}} selected', { count: selectedCount })})
  712. </span>
  713. )}
  714. </div>
  715. <button
  716. onClick={onClose}
  717. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  718. aria-label={t('common.close', 'Close')}
  719. >
  720. <X className="w-5 h-5" />
  721. </button>
  722. </div>
  723. {/* Two columns from md up: which spools on the left, what the label
  724. looks like on the right. Stacked and scrolled as one on phones. */}
  725. <div className="flex-1 min-h-0 overflow-y-auto md:overflow-hidden grid grid-cols-1 md:grid-cols-2">
  726. <div className="flex flex-col min-h-0 md:border-r border-bambu-dark-tertiary">
  727. {/* Search + material chips */}
  728. <div className="p-4 space-y-2 border-b border-bambu-dark-tertiary">
  729. <div className="relative">
  730. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none" />
  731. <input
  732. type="search"
  733. value={search}
  734. onChange={(e) => setSearch(e.target.value)}
  735. placeholder={t('inventory.labels.searchPlaceholder', 'Search name, brand, or #ID')}
  736. 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"
  737. />
  738. </div>
  739. {materials.length > 1 && (
  740. <div className="flex flex-wrap items-center gap-1.5">
  741. <span className="text-xs text-bambu-gray mr-1">
  742. {t('inventory.labels.filterByMaterial', 'Material:')}
  743. </span>
  744. <button
  745. type="button"
  746. onClick={() => setMaterialFilter('')}
  747. className={`px-2 py-0.5 text-xs rounded-full border transition ${
  748. materialFilter === ''
  749. ? 'bg-bambu-green text-bambu-dark border-bambu-green'
  750. : 'bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray'
  751. }`}
  752. >
  753. {t('inventory.labels.allMaterials', 'All')}
  754. </button>
  755. {materials.map((m) => (
  756. <button
  757. key={m}
  758. type="button"
  759. onClick={() => setMaterialFilter(m)}
  760. className={`px-2 py-0.5 text-xs rounded-full border transition ${
  761. materialFilter === m
  762. ? 'bg-bambu-green text-bambu-dark border-bambu-green'
  763. : 'bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray'
  764. }`}
  765. >
  766. {m}
  767. </button>
  768. ))}
  769. </div>
  770. )}
  771. <div className="flex flex-wrap items-center gap-1.5">
  772. <span className="text-xs text-bambu-gray mr-1">
  773. {t('inventory.labels.sortBy.label')}
  774. </span>
  775. <button
  776. type="button"
  777. onClick={() => setSortMode('id')}
  778. className={`px-2 py-0.5 text-xs rounded-full border transition ${
  779. sortMode === 'id'
  780. ? 'bg-bambu-green text-bambu-dark border-bambu-green'
  781. : 'bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray'
  782. }`}
  783. >
  784. {t('inventory.labels.sortBy.id')}
  785. </button>
  786. <button
  787. type="button"
  788. onClick={() => setSortMode('color')}
  789. className={`px-2 py-0.5 text-xs rounded-full border transition ${
  790. sortMode === 'color'
  791. ? 'bg-bambu-green text-bambu-dark border-bambu-green'
  792. : 'bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray'
  793. }`}
  794. >
  795. {t('inventory.labels.sortBy.color')}
  796. </button>
  797. </div>
  798. </div>
  799. {/* Action bar */}
  800. <div className="px-4 pt-3 pb-2 flex items-center justify-between gap-3 flex-wrap">
  801. <span className="text-sm text-bambu-gray">
  802. {t('inventory.labels.pickSpools', 'Pick which spools to print labels for:')}
  803. </span>
  804. <div className="flex items-center gap-3 text-xs">
  805. <button
  806. type="button"
  807. onClick={allVisibleChecked ? deselectVisible : selectAllVisible}
  808. disabled={visibleSpools.length === 0}
  809. className="text-bambu-green hover:underline disabled:opacity-50 disabled:no-underline disabled:cursor-not-allowed"
  810. >
  811. {allVisibleChecked
  812. ? t('inventory.labels.deselectVisible', 'Deselect visible')
  813. : t('inventory.labels.selectVisible', 'Select all visible ({{count}})', {
  814. count: visibleSpools.length,
  815. })}
  816. </button>
  817. <button
  818. type="button"
  819. onClick={clearAll}
  820. disabled={selectedCount === 0}
  821. className="text-bambu-gray hover:text-white hover:underline disabled:opacity-50 disabled:no-underline disabled:cursor-not-allowed"
  822. >
  823. {t('inventory.labels.clearAll', 'Clear all')}
  824. </button>
  825. </div>
  826. </div>
  827. {/* Spool list */}
  828. <div className="flex-1 overflow-y-auto px-2 pb-2 min-h-0 max-h-72 md:max-h-none">
  829. {visibleSpools.length === 0 ? (
  830. <div className="text-center text-sm text-bambu-gray py-6">
  831. {sortedSpools.length === 0
  832. ? t('inventory.labels.noSpoolsToShow', 'No spools to show. Adjust your filter and try again.')
  833. : t('inventory.labels.noMatches', 'No spools match the current search or filter.')}
  834. </div>
  835. ) : (
  836. <ul className="space-y-0.5">
  837. {visibleSpools.map((s) => {
  838. const checked = selectedIds.has(s.id);
  839. return (
  840. <li key={s.id}>
  841. <label className="flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary/50 cursor-pointer">
  842. {checked ? (
  843. <CheckSquare className="w-4 h-4 text-bambu-green shrink-0" />
  844. ) : (
  845. <Square className="w-4 h-4 text-bambu-gray shrink-0" />
  846. )}
  847. <input
  848. type="checkbox"
  849. checked={checked}
  850. onChange={() => toggleOne(s.id)}
  851. className="sr-only"
  852. />
  853. <span
  854. className="w-4 h-4 rounded border border-black/20 shrink-0"
  855. style={swatchStyle(s.rgba)}
  856. />
  857. <span className="flex-1 min-w-0 truncate text-sm text-white">
  858. {spoolDisplayName(s)}
  859. </span>
  860. <span className="text-xs font-mono text-bambu-gray shrink-0">
  861. #{s.id}
  862. </span>
  863. </label>
  864. </li>
  865. );
  866. })}
  867. </ul>
  868. )}
  869. </div>
  870. </div>
  871. <div className="md:overflow-y-auto p-4 space-y-4 border-t md:border-t-0 border-bambu-dark-tertiary">
  872. {/* Label size */}
  873. <div className="space-y-1">
  874. <label htmlFor="label-template" className="text-sm font-medium text-white">
  875. {t('inventory.labels.template', 'Label size')}
  876. </label>
  877. <select
  878. id="label-template"
  879. data-testid="label-template-select"
  880. value={template}
  881. onChange={(e) => chooseTemplate(e.target.value as TemplateChoice)}
  882. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"
  883. >
  884. {TEMPLATE_OPTIONS.map((opt) => (
  885. <option key={opt.value} value={opt.value}>
  886. {t(`inventory.labels.templates.${opt.i18nKey}.label`, opt.fallbackLabel)}
  887. </option>
  888. ))}
  889. {savedTemplates.length > 0 && (
  890. <optgroup label={t('inventory.labels.custom.savedGroup', 'Saved templates')}>
  891. {savedTemplates.map((tpl) => (
  892. <option key={tpl.id} value={savedChoice(tpl.id)}>
  893. {tpl.name}
  894. </option>
  895. ))}
  896. </optgroup>
  897. )}
  898. <option value="custom">{t('inventory.labels.custom.option', 'Custom sheet…')}</option>
  899. </select>
  900. <p data-testid="label-template-hint" className="text-xs text-bambu-gray">
  901. {template === 'custom'
  902. ? t('inventory.labels.custom.hint', 'Describe your own label sheet below.')
  903. : savedId !== null
  904. ? savedTemplate
  905. ? layoutSummary(savedTemplate.layout)
  906. : null
  907. : t(`inventory.labels.templates.${templateOption.i18nKey}.hint`, templateOption.fallbackHint)}
  908. </p>
  909. </div>
  910. {/* A saved template: its sheet, and Edit / Delete for those who may (#3296). */}
  911. {savedTemplate && !editing && (
  912. <div className="space-y-2">
  913. <LabelSheetDiagram layout={savedTemplate.layout} startingPosition={startingPositionIsValid ? startingPosition : 1} />
  914. {canManageTemplates && (
  915. <div className="flex justify-center gap-4 text-xs">
  916. <button
  917. type="button"
  918. data-testid="label-template-edit"
  919. onClick={() =>
  920. setEditing({ name: savedTemplate.name, draft: draftFromLayout(savedTemplate.layout) })
  921. }
  922. className="text-bambu-green hover:underline"
  923. >
  924. {t('inventory.labels.custom.edit', 'Edit')}
  925. </button>
  926. <button
  927. type="button"
  928. data-testid="label-template-delete"
  929. onClick={() => setConfirmDelete(true)}
  930. className="text-red-400 hover:underline"
  931. >
  932. {t('inventory.labels.custom.delete', 'Delete')}
  933. </button>
  934. </div>
  935. )}
  936. </div>
  937. )}
  938. {/* Editing a saved template: the name and the whole layout. */}
  939. {savedTemplate && editing && (
  940. <div className="space-y-3">
  941. <TemplateNameInput
  942. value={editing.name}
  943. onChange={(name) => setEditing({ ...editing, name })}
  944. />
  945. <LabelSheetLayoutEditor
  946. draft={editing.draft}
  947. onChange={(draft) => setEditing({ ...editing, draft })}
  948. problem={problem}
  949. startingPosition={startingPositionIsValid ? startingPosition : 1}
  950. />
  951. <div className="flex flex-wrap justify-end gap-2">
  952. <Button variant="secondary" onClick={() => setEditing(null)} disabled={saveMutation.isPending}>
  953. {t('common.cancel', 'Cancel')}
  954. </Button>
  955. <Button
  956. variant="secondary"
  957. data-testid="label-template-save-as-new"
  958. disabled={!activeLayout || !editing.name.trim() || saveMutation.isPending}
  959. onClick={() => activeLayout && saveNewTemplate(editing.name, activeLayout)}
  960. >
  961. {t('inventory.labels.custom.saveAsNew', 'Save as new')}
  962. </Button>
  963. <Button
  964. data-testid="label-template-save-changes"
  965. disabled={!activeLayout || !editing.name.trim() || saveMutation.isPending}
  966. onClick={() => activeLayout && saveEditedTemplate(savedTemplate.id, editing.name, activeLayout)}
  967. >
  968. {t('inventory.labels.custom.saveChanges', 'Save changes')}
  969. </Button>
  970. </div>
  971. </div>
  972. )}
  973. {/* A one-off custom sheet, and saving it under a name. */}
  974. {template === 'custom' && (
  975. <div className="space-y-3">
  976. <LabelSheetLayoutEditor
  977. draft={prefs.customDraft}
  978. onChange={(customDraft) => updatePrefs({ customDraft })}
  979. problem={problem}
  980. startingPosition={startingPositionIsValid ? startingPosition : 1}
  981. />
  982. {canManageTemplates &&
  983. (newTemplateName === null ? (
  984. <button
  985. type="button"
  986. data-testid="label-template-save-as"
  987. disabled={!activeLayout}
  988. onClick={() => setNewTemplateName('')}
  989. className="text-xs text-bambu-green hover:underline disabled:opacity-50 disabled:no-underline disabled:cursor-not-allowed"
  990. >
  991. {t('inventory.labels.custom.saveAs', 'Save as template…')}
  992. </button>
  993. ) : (
  994. <div className="flex flex-wrap items-end gap-2">
  995. <div className="flex-1 min-w-40">
  996. <TemplateNameInput value={newTemplateName} onChange={setNewTemplateName} autoFocus />
  997. </div>
  998. <Button variant="secondary" onClick={() => setNewTemplateName(null)} disabled={saveMutation.isPending}>
  999. {t('common.cancel', 'Cancel')}
  1000. </Button>
  1001. <Button
  1002. data-testid="label-template-save"
  1003. disabled={!activeLayout || !newTemplateName.trim() || saveMutation.isPending}
  1004. onClick={() => activeLayout && saveNewTemplate(newTemplateName, activeLayout)}
  1005. >
  1006. {t('inventory.labels.custom.save', 'Save')}
  1007. </Button>
  1008. </div>
  1009. ))}
  1010. </div>
  1011. )}
  1012. {/* Preview */}
  1013. <div className="space-y-1">
  1014. <div className="text-sm font-medium text-white">
  1015. {previewSpoolId === null
  1016. ? t('inventory.labels.preview', 'Preview')
  1017. : t('inventory.labels.previewOf', 'Preview of #{{id}}', { id: previewSpoolId })}
  1018. </div>
  1019. <div
  1020. data-testid="label-preview"
  1021. className="relative flex items-center justify-center min-h-40 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary"
  1022. >
  1023. {previewSpoolId === null ? (
  1024. <span className="text-sm text-bambu-gray text-center">
  1025. {t('inventory.labels.previewNoSelection', 'Select a spool to see its label.')}
  1026. </span>
  1027. ) : !sheetReady ? (
  1028. <span className="text-sm text-bambu-gray text-center">
  1029. {t('inventory.labels.custom.previewWaiting', 'The preview appears once the sheet layout is complete.')}
  1030. </span>
  1031. ) : previewError ? (
  1032. <span className="text-sm text-red-400 text-center">
  1033. {t('inventory.labels.previewError', 'Could not render the preview: {{msg}}', { msg: previewError })}
  1034. </span>
  1035. ) : previewUrl ? (
  1036. <img
  1037. src={previewUrl}
  1038. alt={t('inventory.labels.previewAlt', 'Label preview')}
  1039. className="max-h-56 max-w-full object-contain bg-white shadow"
  1040. />
  1041. ) : null}
  1042. {previewLoading && (
  1043. <Loader2 className="absolute top-2 right-2 w-4 h-4 animate-spin text-bambu-green" />
  1044. )}
  1045. </div>
  1046. <p className="text-xs text-bambu-gray">
  1047. {t('inventory.labels.previewHint', 'Lines that don\'t fit on this label size are left out.')}
  1048. </p>
  1049. </div>
  1050. {/* Label content */}
  1051. <fieldset className="space-y-2">
  1052. <div className="flex items-center justify-between gap-2">
  1053. <legend className="text-sm font-medium text-white">
  1054. {t('inventory.labels.content', 'Print on the label')}
  1055. </legend>
  1056. <button
  1057. type="button"
  1058. onClick={() => setFields(DEFAULT_SPOOL_LABEL_FIELDS)}
  1059. className="text-xs text-bambu-green hover:underline"
  1060. >
  1061. {t('inventory.labels.resetFields', 'Reset to default')}
  1062. </button>
  1063. </div>
  1064. <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-3 gap-y-1">
  1065. {SPOOL_LABEL_FIELDS.map((field) => {
  1066. const checked = fields.includes(field);
  1067. const { i18nKey, fallback } = FIELD_LABELS[field];
  1068. return (
  1069. <label
  1070. key={field}
  1071. className="flex items-center gap-2 py-0.5 cursor-pointer select-none"
  1072. >
  1073. {checked ? (
  1074. <CheckSquare className="w-4 h-4 text-bambu-green shrink-0" />
  1075. ) : (
  1076. <Square className="w-4 h-4 text-bambu-gray shrink-0" />
  1077. )}
  1078. <input
  1079. type="checkbox"
  1080. data-testid={`label-field-${field}`}
  1081. checked={checked}
  1082. onChange={() => toggleField(field)}
  1083. className="sr-only"
  1084. />
  1085. <span className="text-sm text-white">
  1086. {t(`inventory.labels.fields.${i18nKey}`, fallback)}
  1087. </span>
  1088. </label>
  1089. );
  1090. })}
  1091. </div>
  1092. </fieldset>
  1093. {/* Print options */}
  1094. <div className="space-y-3">
  1095. <label className="inline-flex items-center gap-2 cursor-pointer select-none">
  1096. {prefs.monochrome ? (
  1097. <CheckSquare className="w-4 h-4 text-bambu-green shrink-0" />
  1098. ) : (
  1099. <Square className="w-4 h-4 text-bambu-gray shrink-0" />
  1100. )}
  1101. <input
  1102. type="checkbox"
  1103. checked={prefs.monochrome}
  1104. onChange={(e) => updatePrefs({ monochrome: e.target.checked })}
  1105. className="sr-only"
  1106. />
  1107. <span className="text-sm text-white">
  1108. {t('inventory.labels.monochrome', 'Monochrome (black & white printer)')}
  1109. </span>
  1110. <span className="text-xs text-bambu-gray">
  1111. {t('inventory.labels.monochromeHint', 'Drops the colour swatch and widens the text')}
  1112. </span>
  1113. </label>
  1114. {sheetCapacity !== undefined && (
  1115. <div className="flex items-start gap-3">
  1116. <label
  1117. htmlFor="label-starting-position"
  1118. className="text-sm text-white whitespace-nowrap pt-1.5"
  1119. >
  1120. {t('inventory.labels.startingPosition', 'Starting label position')}
  1121. </label>
  1122. <input
  1123. id="label-starting-position"
  1124. data-testid="label-starting-position"
  1125. type="number"
  1126. min={1}
  1127. max={sheetCapacity}
  1128. step={1}
  1129. value={startingPositionInput}
  1130. onChange={(event) => setStartingPositionInput(event.target.value)}
  1131. aria-describedby="label-starting-position-help"
  1132. 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"
  1133. />
  1134. <div
  1135. id="label-starting-position-help"
  1136. data-testid="label-starting-position-status"
  1137. className={`text-xs pt-1.5 ${startingPositionIsValid ? 'text-bambu-gray' : 'text-red-400'}`}
  1138. >
  1139. {!startingPositionIsValid
  1140. ? t(
  1141. 'inventory.labels.startingPositionInvalid',
  1142. 'Enter a whole number from 1 to {{capacity}}.',
  1143. { capacity: sheetCapacity },
  1144. )
  1145. : startingPosition === 1
  1146. ? t('inventory.labels.startingPositionFirst', 'Printing starts at position 1.')
  1147. : t(
  1148. 'inventory.labels.startingPositionSkipped',
  1149. 'Positions 1 through {{lastPosition}} will be left blank on the first sheet.',
  1150. { lastPosition: startingPosition - 1 },
  1151. )}
  1152. </div>
  1153. </div>
  1154. )}
  1155. {sheetCapacity !== undefined && (
  1156. <p data-testid="label-scale-hint" className="text-xs text-bambu-gray">
  1157. {t(
  1158. 'inventory.labels.scaleHint',
  1159. 'Print sheets at 100% (actual size), not "Fit to page": a shrunk page drifts off the labels.',
  1160. )}
  1161. </p>
  1162. )}
  1163. <div className="flex flex-wrap items-center gap-1.5">
  1164. <span className="text-sm text-white mr-1">
  1165. {t('inventory.labels.format', 'Output:')}
  1166. </span>
  1167. <button
  1168. type="button"
  1169. data-testid="label-format-pdf"
  1170. aria-pressed={prefs.format === 'pdf'}
  1171. onClick={() => updatePrefs({ format: 'pdf' })}
  1172. className={chipClass(prefs.format === 'pdf')}
  1173. >
  1174. PDF
  1175. </button>
  1176. <button
  1177. type="button"
  1178. data-testid="label-format-png"
  1179. aria-pressed={prefs.format === 'png'}
  1180. onClick={() => updatePrefs({ format: 'png' })}
  1181. className={chipClass(prefs.format === 'png')}
  1182. >
  1183. PNG
  1184. </button>
  1185. {prefs.format === 'png' && (
  1186. <select
  1187. data-testid="label-dpi-select"
  1188. aria-label={t('inventory.labels.dpi', 'Resolution')}
  1189. value={prefs.dpi}
  1190. onChange={(e) => updatePrefs({ dpi: Number(e.target.value) as PngDpi })}
  1191. className="ml-2 px-2 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-xs focus:outline-none focus:border-bambu-green"
  1192. >
  1193. {PNG_DPIS.map((dpi) => (
  1194. <option key={dpi} value={dpi}>
  1195. {dpi} dpi
  1196. </option>
  1197. ))}
  1198. </select>
  1199. )}
  1200. </div>
  1201. {prefs.format === 'png' && (
  1202. <p className="text-xs text-bambu-gray">
  1203. {t(
  1204. 'inventory.labels.pngHint',
  1205. 'For label printer software that takes images. Match your printer\'s resolution; several labels come as a ZIP.',
  1206. )}
  1207. </p>
  1208. )}
  1209. {pngTooLarge && (
  1210. <p data-testid="label-png-too-large" className="text-xs text-red-400">
  1211. {t(
  1212. 'inventory.labels.pngTooLarge',
  1213. 'PNG export is limited to {{maxPages}} sheet pages at {{dpi}} dpi, and this is {{pages}}. Use PDF, a lower resolution or fewer spools.',
  1214. { maxPages: Math.floor(MAX_PNG_SHEET_PAGES_X_DPI / prefs.dpi), dpi: prefs.dpi, pages: pngSheetPages },
  1215. )}
  1216. </p>
  1217. )}
  1218. </div>
  1219. </div>
  1220. </div>
  1221. <div className="flex justify-end gap-2 px-5 py-3 border-t border-bambu-dark-tertiary">
  1222. <Button variant="secondary" onClick={onClose} disabled={pending}>
  1223. {t('common.cancel', 'Cancel')}
  1224. </Button>
  1225. <Button
  1226. data-testid="label-print-button"
  1227. onClick={handlePrint}
  1228. disabled={!canPrint}
  1229. >
  1230. {pending ? (
  1231. <Loader2 className="w-4 h-4 animate-spin" />
  1232. ) : prefs.format === 'pdf' ? (
  1233. <Printer className="w-4 h-4" />
  1234. ) : (
  1235. <Download className="w-4 h-4" />
  1236. )}
  1237. {prefs.format === 'pdf'
  1238. ? t('inventory.labels.createPdf', 'Create PDF')
  1239. : t('inventory.labels.downloadPng', 'Download PNG')}
  1240. </Button>
  1241. </div>
  1242. </div>
  1243. {confirmDelete && savedTemplate && (
  1244. <ConfirmModal
  1245. title={t('inventory.labels.custom.deleteTitle', 'Delete label template')}
  1246. message={t(
  1247. 'inventory.labels.custom.deleteMessage',
  1248. 'Delete "{{name}}" for everyone? Labels already printed are not affected.',
  1249. { name: savedTemplate.name },
  1250. )}
  1251. confirmText={t('inventory.labels.custom.delete', 'Delete')}
  1252. variant="danger"
  1253. overlayZIndex="z-[60]"
  1254. isLoading={deleteMutation.isPending}
  1255. onConfirm={() => deleteSavedTemplate(savedTemplate)}
  1256. onCancel={() => setConfirmDelete(false)}
  1257. />
  1258. )}
  1259. </div>
  1260. );
  1261. }
  1262. function TemplateNameInput({
  1263. value,
  1264. onChange,
  1265. autoFocus = false,
  1266. }: {
  1267. value: string;
  1268. onChange: (name: string) => void;
  1269. autoFocus?: boolean;
  1270. }) {
  1271. const { t } = useTranslation();
  1272. return (
  1273. <label className="block space-y-0.5">
  1274. <span className="text-xs text-bambu-gray">{t('inventory.labels.custom.name', 'Template name')}</span>
  1275. <input
  1276. data-testid="label-template-name"
  1277. type="text"
  1278. maxLength={100}
  1279. autoFocus={autoFocus}
  1280. value={value}
  1281. onChange={(e) => onChange(e.target.value)}
  1282. className="w-full px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:border-bambu-green"
  1283. />
  1284. </label>
  1285. );
  1286. }