LabelTemplatePickerModal.tsx 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  1. import { useEffect, useMemo, useRef, useState } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import { X, Loader2, Printer, CheckSquare, Square, Search, Download } from 'lucide-react';
  4. import {
  5. api,
  6. DEFAULT_SPOOL_LABEL_FIELDS,
  7. SPOOL_LABEL_FIELDS,
  8. type SpoolLabelField,
  9. type SpoolLabelTemplate,
  10. type InventorySpool,
  11. } from '../api/client';
  12. import { Button } from './Button';
  13. import { useToast } from '../contexts/ToastContext';
  14. import { getSwatchStyle, resolveSpoolColorName } from '../utils/colors';
  15. import { useColorCatalogVersion } from '../hooks/useColorCatalogVersion';
  16. /** Subset of InventorySpool the modal needs for checkbox rendering. */
  17. type SpoolForLabel = Pick<
  18. InventorySpool,
  19. 'id' | 'material' | 'subtype' | 'brand' | 'color_name' | 'color_name_is_synthesized' | 'rgba'
  20. >;
  21. interface LabelTemplatePickerModalProps {
  22. isOpen: boolean;
  23. onClose: () => void;
  24. /** All spools the modal can choose from. Typically the page's current
  25. * filter result so the modal stays consistent with what the user sees. */
  26. availableSpools: SpoolForLabel[];
  27. /** IDs to pre-check when the modal opens. Per-card icon passes a single ID;
  28. * the bulk header button passes every visible ID so the user lands in
  29. * "all checked" and refines downward. */
  30. initialSelectedIds: number[];
  31. spoolmanMode: boolean;
  32. }
  33. interface TemplateOption {
  34. value: SpoolLabelTemplate;
  35. i18nKey: string;
  36. fallbackLabel: string;
  37. fallbackHint: string;
  38. }
  39. const TEMPLATE_OPTIONS: TemplateOption[] = [
  40. {
  41. value: 'ams_holder_74x33',
  42. i18nKey: 'amsHolderSmall',
  43. fallbackLabel: 'AMS holder — small (74 × 33 mm)',
  44. fallbackHint: 'Single label per page; matches the printable label from MakerWorld model 752566 (AMS Filament Label Holder).',
  45. },
  46. {
  47. value: 'ams_holder_75x55',
  48. i18nKey: 'amsHolderLarge',
  49. fallbackLabel: 'AMS holder — large (75 × 55 mm)',
  50. 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.',
  51. },
  52. {
  53. value: 'box_40x30',
  54. i18nKey: 'box40x30',
  55. fallbackLabel: 'Box label (40 × 30 mm)',
  56. fallbackHint: 'Single label per page; common DK/Brother roll size, good for filament-bag and storage-bin labels.',
  57. },
  58. {
  59. value: 'box_62x29',
  60. i18nKey: 'box',
  61. fallbackLabel: 'Box label (62 × 29 mm)',
  62. fallbackHint: 'Single label per page; sized for Brother PT/QL and Dymo small labels.',
  63. },
  64. {
  65. value: 'avery_l7160',
  66. i18nKey: 'averyL7160',
  67. fallbackLabel: 'Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)',
  68. fallbackHint: 'EU sheet stock; 21 labels per A4 page.',
  69. },
  70. {
  71. value: 'avery_5160',
  72. i18nKey: 'avery5160',
  73. fallbackLabel: 'Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)',
  74. fallbackHint: 'US sheet stock; 30 labels per Letter page.',
  75. },
  76. ];
  77. const SHEET_CAPACITIES: Partial<Record<SpoolLabelTemplate, number>> = {
  78. avery_l7160: 21,
  79. avery_5160: 30,
  80. };
  81. type OutputFormat = 'pdf' | 'png';
  82. type PngDpi = 203 | 300 | 600;
  83. const PNG_DPIS: PngDpi[] = [203, 300, 600];
  84. // What the checkboxes read, keyed by SpoolLabelField (#2981).
  85. const FIELD_LABELS: Record<SpoolLabelField, { i18nKey: string; fallback: string }> = {
  86. brand: { i18nKey: 'brand', fallback: 'Brand' },
  87. material: { i18nKey: 'material', fallback: 'Material and subtype' },
  88. hex: { i18nKey: 'hex', fallback: 'Colour code' },
  89. name: { i18nKey: 'name', fallback: 'Colour or filament name' },
  90. location: { i18nKey: 'location', fallback: 'Storage location' },
  91. material_number: { i18nKey: 'materialNumber', fallback: 'Material number' },
  92. temps: { i18nKey: 'temps', fallback: 'Nozzle temperature' },
  93. weight: { i18nKey: 'weight', fallback: 'Net weight' },
  94. note: { i18nKey: 'note', fallback: 'Note' },
  95. added: { i18nKey: 'added', fallback: 'Date added' },
  96. qr: { i18nKey: 'qr', fallback: 'QR code' },
  97. spool_id: { i18nKey: 'spoolId', fallback: 'Spool ID' },
  98. };
  99. // Remembered per browser. Printing only needs inventory access, and a server
  100. // setting would need settings access to save.
  101. const PREFS_STORAGE_KEY = 'bambuddy-label-print-options';
  102. interface LabelPrefs {
  103. template: SpoolLabelTemplate;
  104. /** Chosen lines per template: a 40 × 30 roll and an A4 sheet fit different amounts. */
  105. fields: Partial<Record<SpoolLabelTemplate, SpoolLabelField[]>>;
  106. monochrome: boolean;
  107. format: OutputFormat;
  108. dpi: PngDpi;
  109. }
  110. const DEFAULT_PREFS: LabelPrefs = {
  111. template: TEMPLATE_OPTIONS[0].value,
  112. fields: {},
  113. monochrome: false,
  114. format: 'pdf',
  115. dpi: 300,
  116. };
  117. function loadPrefs(): LabelPrefs {
  118. let raw: unknown;
  119. try {
  120. raw = JSON.parse(localStorage.getItem(PREFS_STORAGE_KEY) ?? 'null');
  121. } catch {
  122. return DEFAULT_PREFS;
  123. }
  124. if (!raw || typeof raw !== 'object') return DEFAULT_PREFS;
  125. const r = raw as Partial<Record<keyof LabelPrefs, unknown>>;
  126. const templates = TEMPLATE_OPTIONS.map((o) => o.value);
  127. const fields: LabelPrefs['fields'] = {};
  128. if (r.fields && typeof r.fields === 'object') {
  129. for (const [tpl, list] of Object.entries(r.fields as Record<string, unknown>)) {
  130. if (!templates.includes(tpl as SpoolLabelTemplate) || !Array.isArray(list)) continue;
  131. fields[tpl as SpoolLabelTemplate] = list.filter((f): f is SpoolLabelField =>
  132. (SPOOL_LABEL_FIELDS as readonly string[]).includes(f),
  133. );
  134. }
  135. }
  136. return {
  137. template: templates.includes(r.template as SpoolLabelTemplate)
  138. ? (r.template as SpoolLabelTemplate)
  139. : DEFAULT_PREFS.template,
  140. fields,
  141. monochrome: r.monochrome === true,
  142. format: r.format === 'png' ? 'png' : 'pdf',
  143. dpi: PNG_DPIS.includes(r.dpi as PngDpi) ? (r.dpi as PngDpi) : DEFAULT_PREFS.dpi,
  144. };
  145. }
  146. function savePrefs(prefs: LabelPrefs): void {
  147. try {
  148. localStorage.setItem(PREFS_STORAGE_KEY, JSON.stringify(prefs));
  149. } catch {
  150. // Private mode or storage disabled: the options just aren't remembered.
  151. }
  152. }
  153. function fieldsFor(prefs: LabelPrefs, template: SpoolLabelTemplate): SpoolLabelField[] {
  154. return prefs.fields[template] ?? DEFAULT_SPOOL_LABEL_FIELDS;
  155. }
  156. function openBlobInNewTab(blob: Blob): void {
  157. const url = window.URL.createObjectURL(blob);
  158. // Do NOT pass `noopener,noreferrer`: per the WindowFeatures spec, `noopener`
  159. // forces window.open to return `null` even on success, which made the
  160. // `if (!win)` popup-block fallback below fire on EVERY click — so the blob
  161. // tab opened (downloading a random-named PDF on systems without an inline
  162. // viewer) AND the `<a download>` fallback fired (downloading a second copy
  163. // named bambuddy-labels.pdf). Two identical PDFs per click — issue #1628.
  164. // The blob is same-origin, the destination is a passive PDF tab with no
  165. // script context, and `noreferrer` is a no-op for blob URLs, so dropping
  166. // these flags has no security impact.
  167. const win = window.open(url, '_blank');
  168. if (!win) {
  169. const a = document.createElement('a');
  170. a.href = url;
  171. a.download = 'bambuddy-labels.pdf';
  172. document.body.appendChild(a);
  173. a.click();
  174. document.body.removeChild(a);
  175. }
  176. setTimeout(() => window.URL.revokeObjectURL(url), 60_000);
  177. }
  178. /** Save a PNG, or a ZIP of PNGs when there were several pages. */
  179. function downloadBlob(blob: Blob, template: SpoolLabelTemplate): void {
  180. const url = window.URL.createObjectURL(blob);
  181. const a = document.createElement('a');
  182. a.href = url;
  183. a.download = `bambuddy-labels-${template}.${blob.type === 'application/zip' ? 'zip' : 'png'}`;
  184. document.body.appendChild(a);
  185. a.click();
  186. document.body.removeChild(a);
  187. setTimeout(() => window.URL.revokeObjectURL(url), 60_000);
  188. }
  189. // Thin wrapper over `getSwatchStyle` from utils/colors so the modal's render
  190. // sites keep their existing call shape. Transparent (alpha=00) spools now
  191. // render as a checkerboard pattern instead of collapsing to solid black
  192. // (#1545).
  193. function swatchStyle(rgba: string | null | undefined): React.CSSProperties {
  194. return getSwatchStyle(rgba);
  195. }
  196. function labelColorName(s: SpoolForLabel): string | null {
  197. return resolveSpoolColorName(s.color_name, s.rgba, s.color_name_is_synthesized);
  198. }
  199. function spoolDisplayName(s: SpoolForLabel): string {
  200. // Resolved, not stored: most Bambu spools arrive with no colour name on the
  201. // tag, and picking a label template for "PLA Silk" tells you nothing about
  202. // which of six red spools you are looking at (#3090).
  203. const head = labelColorName(s) ?? `${s.material}${s.subtype ? ` ${s.subtype}` : ''}`;
  204. const brand = s.brand ? ` · ${s.brand}` : '';
  205. return `${head}${brand}`;
  206. }
  207. /** Build a lowercased haystack that the search input matches against. */
  208. function searchableText(s: SpoolForLabel): string {
  209. return [labelColorName(s), s.color_name, s.material, s.subtype, s.brand, `#${s.id}`]
  210. .filter(Boolean)
  211. .join(' ')
  212. .toLowerCase();
  213. }
  214. type SortMode = 'id' | 'color';
  215. /** Sort key for the "by colour" mode (#1410).
  216. *
  217. * Returns a 2-tuple so JS array compare does the right thing without us having
  218. * to spell out a comparator: ``[bucket, position]``. Chromatic colours
  219. * (saturation above the threshold) go in bucket 0 ordered by HSL hue, so the
  220. * sheet reads as a continuous rainbow. Achromatic colours (white / grey /
  221. * black, plus missing/invalid rgba) go in bucket 1 ordered by lightness so the
  222. * neutrals trail at the end of the rainbow going dark → light. Multi-colour
  223. * spools sort on their primary ``rgba``; their ``extra_colors`` stripe is
  224. * still rendered on the label itself but doesn't drive the sort.
  225. */
  226. function colorSortKey(rgba: string | null | undefined): [number, number] {
  227. if (!rgba) return [1, 0]; // unknown colour — bucket with the neutrals at black
  228. const cleaned = rgba.replace(/^#/, '').slice(0, 6);
  229. if (cleaned.length !== 6) return [1, 0];
  230. const r = parseInt(cleaned.slice(0, 2), 16);
  231. const g = parseInt(cleaned.slice(2, 4), 16);
  232. const b = parseInt(cleaned.slice(4, 6), 16);
  233. if ([r, g, b].some(Number.isNaN)) return [1, 0];
  234. const rn = r / 255;
  235. const gn = g / 255;
  236. const bn = b / 255;
  237. const max = Math.max(rn, gn, bn);
  238. const min = Math.min(rn, gn, bn);
  239. const l = (max + min) / 2;
  240. const delta = max - min;
  241. // Saturation in the HSL definition. Achromatic cutoff at 0.1 is generous —
  242. // matches what feels "grey enough" to a user picking colours, without
  243. // sending dark muted colours like deep navy into the neutrals bucket.
  244. const s = delta === 0 ? 0 : delta / (1 - Math.abs(2 * l - 1));
  245. if (s < 0.1) return [1, l]; // neutrals: ordered black → white
  246. let h = 0;
  247. if (max === rn) h = ((gn - bn) / delta) % 6;
  248. else if (max === gn) h = (bn - rn) / delta + 2;
  249. else h = (rn - gn) / delta + 4;
  250. h = h * 60;
  251. if (h < 0) h += 360;
  252. return [0, h]; // chromatic: ordered by hue 0..360
  253. }
  254. export function LabelTemplatePickerModal({
  255. isOpen,
  256. onClose,
  257. availableSpools,
  258. initialSelectedIds,
  259. spoolmanMode,
  260. }: LabelTemplatePickerModalProps) {
  261. const { t } = useTranslation();
  262. // The spool filter below resolves colour names through the catalog; its
  263. // memo has to recompute when the catalog finishes loading (#3090).
  264. const colorCatalogVersion = useColorCatalogVersion();
  265. const { showToast } = useToast();
  266. const [pending, setPending] = useState(false);
  267. const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set());
  268. const [search, setSearch] = useState('');
  269. const [materialFilter, setMaterialFilter] = useState<string>('');
  270. const [sortMode, setSortMode] = useState<SortMode>('id');
  271. const [prefs, setPrefs] = useState<LabelPrefs>(DEFAULT_PREFS);
  272. const [startingPositionInput, setStartingPositionInput] = useState('1');
  273. const [previewUrl, setPreviewUrl] = useState<string | null>(null);
  274. const [previewLoading, setPreviewLoading] = useState(false);
  275. const [previewError, setPreviewError] = useState<string | null>(null);
  276. // The object URL on screen. Freed when its replacement arrives, not when the
  277. // options change, so the old label stays visible while the new one renders.
  278. const previewUrlRef = useRef<string | null>(null);
  279. // Sync from caller and reset transient state on open. Intentionally not
  280. // reactive to props while open — once the user starts editing we don't want
  281. // a parent re-render to clobber their selection / filter / search. The
  282. // label options come back as the user last left them.
  283. useEffect(() => {
  284. if (isOpen) {
  285. const allowed = new Set(availableSpools.map((s) => s.id));
  286. setSelectedIds(new Set(initialSelectedIds.filter((id) => allowed.has(id))));
  287. setSearch('');
  288. setMaterialFilter('');
  289. setSortMode('id');
  290. setPrefs(loadPrefs());
  291. setStartingPositionInput('1');
  292. setPending(false);
  293. }
  294. // eslint-disable-next-line react-hooks/exhaustive-deps
  295. }, [isOpen]);
  296. const sortedSpools = useMemo(() => {
  297. const copy = [...availableSpools];
  298. if (sortMode === 'color') {
  299. copy.sort((a, b) => {
  300. const ka = colorSortKey(a.rgba);
  301. const kb = colorSortKey(b.rgba);
  302. if (ka[0] !== kb[0]) return ka[0] - kb[0];
  303. if (ka[1] !== kb[1]) return ka[1] - kb[1];
  304. // Stable tiebreaker on ID so identical colours print in a deterministic
  305. // order across renders.
  306. return a.id - b.id;
  307. });
  308. return copy;
  309. }
  310. copy.sort((a, b) => a.id - b.id);
  311. return copy;
  312. }, [availableSpools, sortMode]);
  313. // Material chips are derived from the *full* available set so they stay
  314. // stable when search/material filter narrows the visible list.
  315. const materials = useMemo(() => {
  316. const set = new Set<string>();
  317. for (const s of sortedSpools) {
  318. if (s.material) set.add(s.material.toUpperCase());
  319. }
  320. return [...set].sort();
  321. }, [sortedSpools]);
  322. const visibleSpools = useMemo(() => {
  323. // Named so this memo depends on it: searchableText resolves colour names
  324. // through the catalog, which resolveSpoolColorName reads from module state
  325. // the linter cannot follow. Without it a query typed before the catalog
  326. // loads keeps its empty result (#3090).
  327. void colorCatalogVersion;
  328. const q = search.trim().toLowerCase();
  329. return sortedSpools.filter((s) => {
  330. if (materialFilter && (s.material || '').toUpperCase() !== materialFilter) return false;
  331. if (q && !searchableText(s).includes(q)) return false;
  332. return true;
  333. });
  334. }, [sortedSpools, search, materialFilter, colorCatalogVersion]);
  335. const allVisibleChecked =
  336. visibleSpools.length > 0 && visibleSpools.every((s) => selectedIds.has(s.id));
  337. const template = prefs.template;
  338. const fields = fieldsFor(prefs, template);
  339. const fieldsKey = fields.join(',');
  340. // The preview shows the first spool that will print, in print order.
  341. const previewSpoolId = sortedSpools.find((s) => selectedIds.has(s.id))?.id ?? null;
  342. function showPreview(url: string | null) {
  343. if (previewUrlRef.current) window.URL.revokeObjectURL(previewUrlRef.current);
  344. previewUrlRef.current = url;
  345. setPreviewUrl(url);
  346. }
  347. // Re-render the preview a moment after the last change, dropping any
  348. // request still in flight so a slow answer can't overwrite a newer one.
  349. useEffect(() => {
  350. if (!isOpen || previewSpoolId === null) {
  351. showPreview(null);
  352. setPreviewError(null);
  353. setPreviewLoading(false);
  354. return;
  355. }
  356. const controller = new AbortController();
  357. setPreviewLoading(true);
  358. const timer = window.setTimeout(async () => {
  359. const request = {
  360. spool_id: previewSpoolId,
  361. template,
  362. monochrome: prefs.monochrome,
  363. fields: fieldsKey ? (fieldsKey.split(',') as SpoolLabelField[]) : [],
  364. };
  365. try {
  366. const blob = spoolmanMode
  367. ? await api.previewSpoolmanSpoolLabel(request, controller.signal)
  368. : await api.previewSpoolLabel(request, controller.signal);
  369. if (controller.signal.aborted) return;
  370. showPreview(window.URL.createObjectURL(blob));
  371. setPreviewError(null);
  372. } catch (err) {
  373. if (controller.signal.aborted) return;
  374. showPreview(null);
  375. setPreviewError(err instanceof Error ? err.message : String(err));
  376. } finally {
  377. if (!controller.signal.aborted) setPreviewLoading(false);
  378. }
  379. }, 250);
  380. return () => {
  381. window.clearTimeout(timer);
  382. controller.abort();
  383. };
  384. }, [isOpen, previewSpoolId, template, fieldsKey, prefs.monochrome, spoolmanMode]);
  385. // Free the last preview when the modal unmounts.
  386. useEffect(
  387. () => () => {
  388. if (previewUrlRef.current) window.URL.revokeObjectURL(previewUrlRef.current);
  389. },
  390. [],
  391. );
  392. if (!isOpen) return null;
  393. const selectedCount = selectedIds.size;
  394. const noSelection = selectedCount === 0;
  395. const sheetCapacity = SHEET_CAPACITIES[template];
  396. const startingPosition = Number(startingPositionInput);
  397. const startingPositionIsValid =
  398. sheetCapacity === undefined ||
  399. (Number.isInteger(startingPosition) && startingPosition >= 1 && startingPosition <= sheetCapacity);
  400. const templateOption = TEMPLATE_OPTIONS.find((o) => o.value === template) ?? TEMPLATE_OPTIONS[0];
  401. function updatePrefs(change: Partial<LabelPrefs>) {
  402. setPrefs((prev) => {
  403. const next = { ...prev, ...change };
  404. savePrefs(next);
  405. return next;
  406. });
  407. }
  408. function setFields(next: SpoolLabelField[]) {
  409. // Stored in print order, so the saved list reads like the label.
  410. const ordered = SPOOL_LABEL_FIELDS.filter((f) => next.includes(f));
  411. updatePrefs({ fields: { ...prefs.fields, [template]: ordered } });
  412. }
  413. function toggleField(field: SpoolLabelField) {
  414. setFields(fields.includes(field) ? fields.filter((f) => f !== field) : [...fields, field]);
  415. }
  416. function toggleOne(id: number) {
  417. setSelectedIds((prev) => {
  418. const next = new Set(prev);
  419. if (next.has(id)) next.delete(id);
  420. else next.add(id);
  421. return next;
  422. });
  423. }
  424. function selectAllVisible() {
  425. setSelectedIds((prev) => {
  426. const next = new Set(prev);
  427. for (const s of visibleSpools) next.add(s.id);
  428. return next;
  429. });
  430. }
  431. function deselectVisible() {
  432. setSelectedIds((prev) => {
  433. const next = new Set(prev);
  434. for (const s of visibleSpools) next.delete(s.id);
  435. return next;
  436. });
  437. }
  438. function clearAll() {
  439. setSelectedIds(new Set());
  440. }
  441. async function handlePrint() {
  442. if (noSelection || pending || !startingPositionIsValid) return;
  443. // Order matters: the backend (labels.py) prints labels in the same order
  444. // we send IDs. Use the sorted list so a "by colour" sort flows through to
  445. // the output instead of being clobbered by an ascending-ID re-sort.
  446. const ids = sortedSpools.filter((s) => selectedIds.has(s.id)).map((s) => s.id);
  447. const request = {
  448. spool_ids: ids,
  449. template,
  450. monochrome: prefs.monochrome,
  451. starting_position: sheetCapacity === undefined ? 1 : startingPosition,
  452. fields,
  453. format: prefs.format,
  454. dpi: prefs.dpi,
  455. };
  456. setPending(true);
  457. try {
  458. const blob = spoolmanMode
  459. ? await api.printSpoolmanSpoolLabels(request)
  460. : await api.printSpoolLabels(request);
  461. if (prefs.format === 'pdf') openBlobInNewTab(blob);
  462. else downloadBlob(blob, template);
  463. onClose();
  464. } catch (err) {
  465. const msg = err instanceof Error ? err.message : String(err);
  466. showToast(
  467. t('inventory.labels.error', 'Could not generate labels: {{msg}}', { msg }),
  468. 'error',
  469. );
  470. } finally {
  471. setPending(false);
  472. }
  473. }
  474. const chipClass = (active: boolean) =>
  475. `px-2 py-0.5 text-xs rounded-full border transition ${
  476. active
  477. ? 'bg-bambu-green text-bambu-dark border-bambu-green'
  478. : 'bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray'
  479. }`;
  480. return (
  481. <div className="fixed inset-0 z-50 flex items-start sm:items-center justify-center p-4 overflow-y-auto">
  482. <div
  483. className="absolute inset-0 bg-black/60 backdrop-blur-sm"
  484. onClick={onClose}
  485. />
  486. <div
  487. data-testid="label-template-picker-panel"
  488. 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"
  489. >
  490. {/* Header */}
  491. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  492. <div className="flex items-center gap-2">
  493. <Printer className="w-5 h-5 text-bambu-green" />
  494. <h2 className="text-lg font-semibold text-white">
  495. {t('inventory.labels.title', 'Print spool labels')}
  496. </h2>
  497. {selectedCount > 0 && (
  498. <span className="text-sm text-bambu-gray">
  499. ({t('inventory.labels.selectedCount', '{{count}} selected', { count: selectedCount })})
  500. </span>
  501. )}
  502. </div>
  503. <button
  504. onClick={onClose}
  505. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  506. aria-label={t('common.close', 'Close')}
  507. >
  508. <X className="w-5 h-5" />
  509. </button>
  510. </div>
  511. {/* Two columns from md up: which spools on the left, what the label
  512. looks like on the right. Stacked and scrolled as one on phones. */}
  513. <div className="flex-1 min-h-0 overflow-y-auto md:overflow-hidden grid grid-cols-1 md:grid-cols-2">
  514. <div className="flex flex-col min-h-0 md:border-r border-bambu-dark-tertiary">
  515. {/* Search + material chips */}
  516. <div className="p-4 space-y-2 border-b border-bambu-dark-tertiary">
  517. <div className="relative">
  518. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none" />
  519. <input
  520. type="search"
  521. value={search}
  522. onChange={(e) => setSearch(e.target.value)}
  523. placeholder={t('inventory.labels.searchPlaceholder', 'Search name, brand, or #ID')}
  524. 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"
  525. />
  526. </div>
  527. {materials.length > 1 && (
  528. <div className="flex flex-wrap items-center gap-1.5">
  529. <span className="text-xs text-bambu-gray mr-1">
  530. {t('inventory.labels.filterByMaterial', 'Material:')}
  531. </span>
  532. <button
  533. type="button"
  534. onClick={() => setMaterialFilter('')}
  535. className={`px-2 py-0.5 text-xs rounded-full border transition ${
  536. materialFilter === ''
  537. ? 'bg-bambu-green text-bambu-dark border-bambu-green'
  538. : 'bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray'
  539. }`}
  540. >
  541. {t('inventory.labels.allMaterials', 'All')}
  542. </button>
  543. {materials.map((m) => (
  544. <button
  545. key={m}
  546. type="button"
  547. onClick={() => setMaterialFilter(m)}
  548. className={`px-2 py-0.5 text-xs rounded-full border transition ${
  549. materialFilter === m
  550. ? 'bg-bambu-green text-bambu-dark border-bambu-green'
  551. : 'bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray'
  552. }`}
  553. >
  554. {m}
  555. </button>
  556. ))}
  557. </div>
  558. )}
  559. <div className="flex flex-wrap items-center gap-1.5">
  560. <span className="text-xs text-bambu-gray mr-1">
  561. {t('inventory.labels.sortBy.label')}
  562. </span>
  563. <button
  564. type="button"
  565. onClick={() => setSortMode('id')}
  566. className={`px-2 py-0.5 text-xs rounded-full border transition ${
  567. sortMode === 'id'
  568. ? 'bg-bambu-green text-bambu-dark border-bambu-green'
  569. : 'bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray'
  570. }`}
  571. >
  572. {t('inventory.labels.sortBy.id')}
  573. </button>
  574. <button
  575. type="button"
  576. onClick={() => setSortMode('color')}
  577. className={`px-2 py-0.5 text-xs rounded-full border transition ${
  578. sortMode === 'color'
  579. ? 'bg-bambu-green text-bambu-dark border-bambu-green'
  580. : 'bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray'
  581. }`}
  582. >
  583. {t('inventory.labels.sortBy.color')}
  584. </button>
  585. </div>
  586. </div>
  587. {/* Action bar */}
  588. <div className="px-4 pt-3 pb-2 flex items-center justify-between gap-3 flex-wrap">
  589. <span className="text-sm text-bambu-gray">
  590. {t('inventory.labels.pickSpools', 'Pick which spools to print labels for:')}
  591. </span>
  592. <div className="flex items-center gap-3 text-xs">
  593. <button
  594. type="button"
  595. onClick={allVisibleChecked ? deselectVisible : selectAllVisible}
  596. disabled={visibleSpools.length === 0}
  597. className="text-bambu-green hover:underline disabled:opacity-50 disabled:no-underline disabled:cursor-not-allowed"
  598. >
  599. {allVisibleChecked
  600. ? t('inventory.labels.deselectVisible', 'Deselect visible')
  601. : t('inventory.labels.selectVisible', 'Select all visible ({{count}})', {
  602. count: visibleSpools.length,
  603. })}
  604. </button>
  605. <button
  606. type="button"
  607. onClick={clearAll}
  608. disabled={selectedCount === 0}
  609. className="text-bambu-gray hover:text-white hover:underline disabled:opacity-50 disabled:no-underline disabled:cursor-not-allowed"
  610. >
  611. {t('inventory.labels.clearAll', 'Clear all')}
  612. </button>
  613. </div>
  614. </div>
  615. {/* Spool list */}
  616. <div className="flex-1 overflow-y-auto px-2 pb-2 min-h-0 max-h-72 md:max-h-none">
  617. {visibleSpools.length === 0 ? (
  618. <div className="text-center text-sm text-bambu-gray py-6">
  619. {sortedSpools.length === 0
  620. ? t('inventory.labels.noSpoolsToShow', 'No spools to show. Adjust your filter and try again.')
  621. : t('inventory.labels.noMatches', 'No spools match the current search or filter.')}
  622. </div>
  623. ) : (
  624. <ul className="space-y-0.5">
  625. {visibleSpools.map((s) => {
  626. const checked = selectedIds.has(s.id);
  627. return (
  628. <li key={s.id}>
  629. <label className="flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary/50 cursor-pointer">
  630. {checked ? (
  631. <CheckSquare className="w-4 h-4 text-bambu-green shrink-0" />
  632. ) : (
  633. <Square className="w-4 h-4 text-bambu-gray shrink-0" />
  634. )}
  635. <input
  636. type="checkbox"
  637. checked={checked}
  638. onChange={() => toggleOne(s.id)}
  639. className="sr-only"
  640. />
  641. <span
  642. className="w-4 h-4 rounded border border-black/20 shrink-0"
  643. style={swatchStyle(s.rgba)}
  644. />
  645. <span className="flex-1 min-w-0 truncate text-sm text-white">
  646. {spoolDisplayName(s)}
  647. </span>
  648. <span className="text-xs font-mono text-bambu-gray shrink-0">
  649. #{s.id}
  650. </span>
  651. </label>
  652. </li>
  653. );
  654. })}
  655. </ul>
  656. )}
  657. </div>
  658. </div>
  659. <div className="md:overflow-y-auto p-4 space-y-4 border-t md:border-t-0 border-bambu-dark-tertiary">
  660. {/* Label size */}
  661. <div className="space-y-1">
  662. <label htmlFor="label-template" className="text-sm font-medium text-white">
  663. {t('inventory.labels.template', 'Label size')}
  664. </label>
  665. <select
  666. id="label-template"
  667. data-testid="label-template-select"
  668. value={template}
  669. onChange={(e) => updatePrefs({ template: e.target.value as SpoolLabelTemplate })}
  670. 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"
  671. >
  672. {TEMPLATE_OPTIONS.map((opt) => (
  673. <option key={opt.value} value={opt.value}>
  674. {t(`inventory.labels.templates.${opt.i18nKey}.label`, opt.fallbackLabel)}
  675. </option>
  676. ))}
  677. </select>
  678. <p className="text-xs text-bambu-gray">
  679. {t(`inventory.labels.templates.${templateOption.i18nKey}.hint`, templateOption.fallbackHint)}
  680. </p>
  681. </div>
  682. {/* Preview */}
  683. <div className="space-y-1">
  684. <div className="text-sm font-medium text-white">
  685. {previewSpoolId === null
  686. ? t('inventory.labels.preview', 'Preview')
  687. : t('inventory.labels.previewOf', 'Preview of #{{id}}', { id: previewSpoolId })}
  688. </div>
  689. <div
  690. data-testid="label-preview"
  691. className="relative flex items-center justify-center min-h-40 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary"
  692. >
  693. {previewSpoolId === null ? (
  694. <span className="text-sm text-bambu-gray text-center">
  695. {t('inventory.labels.previewNoSelection', 'Select a spool to see its label.')}
  696. </span>
  697. ) : previewError ? (
  698. <span className="text-sm text-red-400 text-center">
  699. {t('inventory.labels.previewError', 'Could not render the preview: {{msg}}', { msg: previewError })}
  700. </span>
  701. ) : previewUrl ? (
  702. <img
  703. src={previewUrl}
  704. alt={t('inventory.labels.previewAlt', 'Label preview')}
  705. className="max-h-56 max-w-full object-contain bg-white shadow"
  706. />
  707. ) : null}
  708. {previewLoading && (
  709. <Loader2 className="absolute top-2 right-2 w-4 h-4 animate-spin text-bambu-green" />
  710. )}
  711. </div>
  712. <p className="text-xs text-bambu-gray">
  713. {t('inventory.labels.previewHint', 'Lines that don\'t fit on this label size are left out.')}
  714. </p>
  715. </div>
  716. {/* Label content */}
  717. <fieldset className="space-y-2">
  718. <div className="flex items-center justify-between gap-2">
  719. <legend className="text-sm font-medium text-white">
  720. {t('inventory.labels.content', 'Print on the label')}
  721. </legend>
  722. <button
  723. type="button"
  724. onClick={() => setFields(DEFAULT_SPOOL_LABEL_FIELDS)}
  725. className="text-xs text-bambu-green hover:underline"
  726. >
  727. {t('inventory.labels.resetFields', 'Reset to default')}
  728. </button>
  729. </div>
  730. <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-3 gap-y-1">
  731. {SPOOL_LABEL_FIELDS.map((field) => {
  732. const checked = fields.includes(field);
  733. const { i18nKey, fallback } = FIELD_LABELS[field];
  734. return (
  735. <label
  736. key={field}
  737. className="flex items-center gap-2 py-0.5 cursor-pointer select-none"
  738. >
  739. {checked ? (
  740. <CheckSquare className="w-4 h-4 text-bambu-green shrink-0" />
  741. ) : (
  742. <Square className="w-4 h-4 text-bambu-gray shrink-0" />
  743. )}
  744. <input
  745. type="checkbox"
  746. data-testid={`label-field-${field}`}
  747. checked={checked}
  748. onChange={() => toggleField(field)}
  749. className="sr-only"
  750. />
  751. <span className="text-sm text-white">
  752. {t(`inventory.labels.fields.${i18nKey}`, fallback)}
  753. </span>
  754. </label>
  755. );
  756. })}
  757. </div>
  758. </fieldset>
  759. {/* Print options */}
  760. <div className="space-y-3">
  761. <label className="inline-flex items-center gap-2 cursor-pointer select-none">
  762. {prefs.monochrome ? (
  763. <CheckSquare className="w-4 h-4 text-bambu-green shrink-0" />
  764. ) : (
  765. <Square className="w-4 h-4 text-bambu-gray shrink-0" />
  766. )}
  767. <input
  768. type="checkbox"
  769. checked={prefs.monochrome}
  770. onChange={(e) => updatePrefs({ monochrome: e.target.checked })}
  771. className="sr-only"
  772. />
  773. <span className="text-sm text-white">
  774. {t('inventory.labels.monochrome', 'Monochrome (black & white printer)')}
  775. </span>
  776. <span className="text-xs text-bambu-gray">
  777. {t('inventory.labels.monochromeHint', 'Drops the colour swatch and widens the text')}
  778. </span>
  779. </label>
  780. {sheetCapacity !== undefined && (
  781. <div className="flex items-start gap-3">
  782. <label
  783. htmlFor="label-starting-position"
  784. className="text-sm text-white whitespace-nowrap pt-1.5"
  785. >
  786. {t('inventory.labels.startingPosition', 'Starting label position')}
  787. </label>
  788. <input
  789. id="label-starting-position"
  790. data-testid="label-starting-position"
  791. type="number"
  792. min={1}
  793. max={sheetCapacity}
  794. step={1}
  795. value={startingPositionInput}
  796. onChange={(event) => setStartingPositionInput(event.target.value)}
  797. aria-describedby="label-starting-position-help"
  798. 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"
  799. />
  800. <div
  801. id="label-starting-position-help"
  802. data-testid="label-starting-position-status"
  803. className={`text-xs pt-1.5 ${startingPositionIsValid ? 'text-bambu-gray' : 'text-red-400'}`}
  804. >
  805. {!startingPositionIsValid
  806. ? t(
  807. 'inventory.labels.startingPositionInvalid',
  808. 'Enter a whole number from 1 to {{capacity}}.',
  809. { capacity: sheetCapacity },
  810. )
  811. : startingPosition === 1
  812. ? t('inventory.labels.startingPositionFirst', 'Printing starts at position 1.')
  813. : t(
  814. 'inventory.labels.startingPositionSkipped',
  815. 'Positions 1 through {{lastPosition}} will be left blank on the first sheet.',
  816. { lastPosition: startingPosition - 1 },
  817. )}
  818. </div>
  819. </div>
  820. )}
  821. <div className="flex flex-wrap items-center gap-1.5">
  822. <span className="text-sm text-white mr-1">
  823. {t('inventory.labels.format', 'Output:')}
  824. </span>
  825. <button
  826. type="button"
  827. data-testid="label-format-pdf"
  828. aria-pressed={prefs.format === 'pdf'}
  829. onClick={() => updatePrefs({ format: 'pdf' })}
  830. className={chipClass(prefs.format === 'pdf')}
  831. >
  832. PDF
  833. </button>
  834. <button
  835. type="button"
  836. data-testid="label-format-png"
  837. aria-pressed={prefs.format === 'png'}
  838. onClick={() => updatePrefs({ format: 'png' })}
  839. className={chipClass(prefs.format === 'png')}
  840. >
  841. PNG
  842. </button>
  843. {prefs.format === 'png' && (
  844. <select
  845. data-testid="label-dpi-select"
  846. aria-label={t('inventory.labels.dpi', 'Resolution')}
  847. value={prefs.dpi}
  848. onChange={(e) => updatePrefs({ dpi: Number(e.target.value) as PngDpi })}
  849. 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"
  850. >
  851. {PNG_DPIS.map((dpi) => (
  852. <option key={dpi} value={dpi}>
  853. {dpi} dpi
  854. </option>
  855. ))}
  856. </select>
  857. )}
  858. </div>
  859. {prefs.format === 'png' && (
  860. <p className="text-xs text-bambu-gray">
  861. {t(
  862. 'inventory.labels.pngHint',
  863. 'For label printer software that takes images. Match your printer\'s resolution; several labels come as a ZIP.',
  864. )}
  865. </p>
  866. )}
  867. </div>
  868. </div>
  869. </div>
  870. <div className="flex justify-end gap-2 px-5 py-3 border-t border-bambu-dark-tertiary">
  871. <Button variant="secondary" onClick={onClose} disabled={pending}>
  872. {t('common.cancel', 'Cancel')}
  873. </Button>
  874. <Button
  875. data-testid="label-print-button"
  876. onClick={handlePrint}
  877. disabled={noSelection || pending || !startingPositionIsValid}
  878. >
  879. {pending ? (
  880. <Loader2 className="w-4 h-4 animate-spin" />
  881. ) : prefs.format === 'pdf' ? (
  882. <Printer className="w-4 h-4" />
  883. ) : (
  884. <Download className="w-4 h-4" />
  885. )}
  886. {prefs.format === 'pdf'
  887. ? t('inventory.labels.createPdf', 'Create PDF')
  888. : t('inventory.labels.downloadPng', 'Download PNG')}
  889. </Button>
  890. </div>
  891. </div>
  892. </div>
  893. );
  894. }