LabelTemplatePickerModal.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. import { useEffect, useMemo, useState } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import { X, Loader2, Printer, CheckSquare, Square, Search } from 'lucide-react';
  4. import { api, type SpoolLabelTemplate, type InventorySpool } from '../api/client';
  5. import { Button } from './Button';
  6. import { useToast } from '../contexts/ToastContext';
  7. import { getSwatchStyle } from '../utils/colors';
  8. /** Subset of InventorySpool the modal needs for checkbox rendering. */
  9. type SpoolForLabel = Pick<
  10. InventorySpool,
  11. 'id' | 'material' | 'subtype' | 'brand' | 'color_name' | 'rgba'
  12. >;
  13. interface LabelTemplatePickerModalProps {
  14. isOpen: boolean;
  15. onClose: () => void;
  16. /** All spools the modal can choose from. Typically the page's current
  17. * filter result so the modal stays consistent with what the user sees. */
  18. availableSpools: SpoolForLabel[];
  19. /** IDs to pre-check when the modal opens. Per-card icon passes a single ID;
  20. * the bulk header button passes every visible ID so the user lands in
  21. * "all checked" and refines downward. */
  22. initialSelectedIds: number[];
  23. spoolmanMode: boolean;
  24. }
  25. interface TemplateOption {
  26. value: SpoolLabelTemplate;
  27. i18nKey: string;
  28. fallbackLabel: string;
  29. fallbackHint: string;
  30. }
  31. const TEMPLATE_OPTIONS: TemplateOption[] = [
  32. {
  33. value: 'ams_holder_74x33',
  34. i18nKey: 'amsHolderSmall',
  35. fallbackLabel: 'AMS holder — small (74 × 33 mm)',
  36. fallbackHint: 'Single label per page; matches the printable label from MakerWorld model 752566 (AMS Filament Label Holder).',
  37. },
  38. {
  39. value: 'ams_holder_75x55',
  40. i18nKey: 'amsHolderLarge',
  41. fallbackLabel: 'AMS holder — large (75 × 55 mm)',
  42. 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.',
  43. },
  44. {
  45. value: 'box_40x30',
  46. i18nKey: 'box40x30',
  47. fallbackLabel: 'Box label (40 × 30 mm)',
  48. fallbackHint: 'Single label per page; common DK/Brother roll size, good for filament-bag and storage-bin labels.',
  49. },
  50. {
  51. value: 'box_62x29',
  52. i18nKey: 'box',
  53. fallbackLabel: 'Box label (62 × 29 mm)',
  54. fallbackHint: 'Single label per page; sized for Brother PT/QL and Dymo small labels.',
  55. },
  56. {
  57. value: 'avery_l7160',
  58. i18nKey: 'averyL7160',
  59. fallbackLabel: 'Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)',
  60. fallbackHint: 'EU sheet stock; 21 labels per A4 page.',
  61. },
  62. {
  63. value: 'avery_5160',
  64. i18nKey: 'avery5160',
  65. fallbackLabel: 'Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)',
  66. fallbackHint: 'US sheet stock; 30 labels per Letter page.',
  67. },
  68. ];
  69. const SHEET_CAPACITIES: Partial<Record<SpoolLabelTemplate, number>> = {
  70. avery_l7160: 21,
  71. avery_5160: 30,
  72. };
  73. const MAX_SHEET_CAPACITY = Math.max(...Object.values(SHEET_CAPACITIES));
  74. function openBlobInNewTab(blob: Blob): void {
  75. const url = window.URL.createObjectURL(blob);
  76. // Do NOT pass `noopener,noreferrer`: per the WindowFeatures spec, `noopener`
  77. // forces window.open to return `null` even on success, which made the
  78. // `if (!win)` popup-block fallback below fire on EVERY click — so the blob
  79. // tab opened (downloading a random-named PDF on systems without an inline
  80. // viewer) AND the `<a download>` fallback fired (downloading a second copy
  81. // named bambuddy-labels.pdf). Two identical PDFs per click — issue #1628.
  82. // The blob is same-origin, the destination is a passive PDF tab with no
  83. // script context, and `noreferrer` is a no-op for blob URLs, so dropping
  84. // these flags has no security impact.
  85. const win = window.open(url, '_blank');
  86. if (!win) {
  87. const a = document.createElement('a');
  88. a.href = url;
  89. a.download = 'bambuddy-labels.pdf';
  90. document.body.appendChild(a);
  91. a.click();
  92. document.body.removeChild(a);
  93. }
  94. setTimeout(() => window.URL.revokeObjectURL(url), 60_000);
  95. }
  96. // Thin wrapper over `getSwatchStyle` from utils/colors so the modal's render
  97. // sites keep their existing call shape. Transparent (alpha=00) spools now
  98. // render as a checkerboard pattern instead of collapsing to solid black
  99. // (#1545).
  100. function swatchStyle(rgba: string | null | undefined): React.CSSProperties {
  101. return getSwatchStyle(rgba);
  102. }
  103. function spoolDisplayName(s: SpoolForLabel): string {
  104. const head = s.color_name ?? `${s.material}${s.subtype ? ` ${s.subtype}` : ''}`;
  105. const brand = s.brand ? ` · ${s.brand}` : '';
  106. return `${head}${brand}`;
  107. }
  108. /** Build a lowercased haystack that the search input matches against. */
  109. function searchableText(s: SpoolForLabel): string {
  110. return [s.color_name, s.material, s.subtype, s.brand, `#${s.id}`]
  111. .filter(Boolean)
  112. .join(' ')
  113. .toLowerCase();
  114. }
  115. type SortMode = 'id' | 'color';
  116. /** Sort key for the "by colour" mode (#1410).
  117. *
  118. * Returns a 2-tuple so JS array compare does the right thing without us having
  119. * to spell out a comparator: ``[bucket, position]``. Chromatic colours
  120. * (saturation above the threshold) go in bucket 0 ordered by HSL hue, so the
  121. * sheet reads as a continuous rainbow. Achromatic colours (white / grey /
  122. * black, plus missing/invalid rgba) go in bucket 1 ordered by lightness so the
  123. * neutrals trail at the end of the rainbow going dark → light. Multi-colour
  124. * spools sort on their primary ``rgba``; their ``extra_colors`` stripe is
  125. * still rendered on the label itself but doesn't drive the sort.
  126. */
  127. function colorSortKey(rgba: string | null | undefined): [number, number] {
  128. if (!rgba) return [1, 0]; // unknown colour — bucket with the neutrals at black
  129. const cleaned = rgba.replace(/^#/, '').slice(0, 6);
  130. if (cleaned.length !== 6) return [1, 0];
  131. const r = parseInt(cleaned.slice(0, 2), 16);
  132. const g = parseInt(cleaned.slice(2, 4), 16);
  133. const b = parseInt(cleaned.slice(4, 6), 16);
  134. if ([r, g, b].some(Number.isNaN)) return [1, 0];
  135. const rn = r / 255;
  136. const gn = g / 255;
  137. const bn = b / 255;
  138. const max = Math.max(rn, gn, bn);
  139. const min = Math.min(rn, gn, bn);
  140. const l = (max + min) / 2;
  141. const delta = max - min;
  142. // Saturation in the HSL definition. Achromatic cutoff at 0.1 is generous —
  143. // matches what feels "grey enough" to a user picking colours, without
  144. // sending dark muted colours like deep navy into the neutrals bucket.
  145. const s = delta === 0 ? 0 : delta / (1 - Math.abs(2 * l - 1));
  146. if (s < 0.1) return [1, l]; // neutrals: ordered black → white
  147. let h = 0;
  148. if (max === rn) h = ((gn - bn) / delta) % 6;
  149. else if (max === gn) h = (bn - rn) / delta + 2;
  150. else h = (rn - gn) / delta + 4;
  151. h = h * 60;
  152. if (h < 0) h += 360;
  153. return [0, h]; // chromatic: ordered by hue 0..360
  154. }
  155. export function LabelTemplatePickerModal({
  156. isOpen,
  157. onClose,
  158. availableSpools,
  159. initialSelectedIds,
  160. spoolmanMode,
  161. }: LabelTemplatePickerModalProps) {
  162. const { t } = useTranslation();
  163. const { showToast } = useToast();
  164. const [pending, setPending] = useState<SpoolLabelTemplate | null>(null);
  165. const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set());
  166. const [search, setSearch] = useState('');
  167. const [materialFilter, setMaterialFilter] = useState<string>('');
  168. const [sortMode, setSortMode] = useState<SortMode>('id');
  169. const [monochrome, setMonochrome] = useState(false);
  170. const [startingPositionInput, setStartingPositionInput] = useState('1');
  171. // Sync from caller and reset transient state on open. Intentionally not
  172. // reactive to props while open — once the user starts editing we don't want
  173. // a parent re-render to clobber their selection / filter / search.
  174. useEffect(() => {
  175. if (isOpen) {
  176. const allowed = new Set(availableSpools.map((s) => s.id));
  177. setSelectedIds(new Set(initialSelectedIds.filter((id) => allowed.has(id))));
  178. setSearch('');
  179. setMaterialFilter('');
  180. setSortMode('id');
  181. setMonochrome(false);
  182. setStartingPositionInput('1');
  183. setPending(null);
  184. }
  185. // eslint-disable-next-line react-hooks/exhaustive-deps
  186. }, [isOpen]);
  187. const sortedSpools = useMemo(() => {
  188. const copy = [...availableSpools];
  189. if (sortMode === 'color') {
  190. copy.sort((a, b) => {
  191. const ka = colorSortKey(a.rgba);
  192. const kb = colorSortKey(b.rgba);
  193. if (ka[0] !== kb[0]) return ka[0] - kb[0];
  194. if (ka[1] !== kb[1]) return ka[1] - kb[1];
  195. // Stable tiebreaker on ID so identical colours print in a deterministic
  196. // order across renders.
  197. return a.id - b.id;
  198. });
  199. return copy;
  200. }
  201. copy.sort((a, b) => a.id - b.id);
  202. return copy;
  203. }, [availableSpools, sortMode]);
  204. // Material chips are derived from the *full* available set so they stay
  205. // stable when search/material filter narrows the visible list.
  206. const materials = useMemo(() => {
  207. const set = new Set<string>();
  208. for (const s of sortedSpools) {
  209. if (s.material) set.add(s.material.toUpperCase());
  210. }
  211. return [...set].sort();
  212. }, [sortedSpools]);
  213. const visibleSpools = useMemo(() => {
  214. const q = search.trim().toLowerCase();
  215. return sortedSpools.filter((s) => {
  216. if (materialFilter && (s.material || '').toUpperCase() !== materialFilter) return false;
  217. if (q && !searchableText(s).includes(q)) return false;
  218. return true;
  219. });
  220. }, [sortedSpools, search, materialFilter]);
  221. const allVisibleChecked =
  222. visibleSpools.length > 0 && visibleSpools.every((s) => selectedIds.has(s.id));
  223. if (!isOpen) return null;
  224. const selectedCount = selectedIds.size;
  225. const noSelection = selectedCount === 0;
  226. const startingPosition = Number(startingPositionInput);
  227. const startingPositionIsValid =
  228. Number.isInteger(startingPosition) &&
  229. startingPosition >= 1 &&
  230. startingPosition <= MAX_SHEET_CAPACITY;
  231. function toggleOne(id: number) {
  232. setSelectedIds((prev) => {
  233. const next = new Set(prev);
  234. if (next.has(id)) next.delete(id);
  235. else next.add(id);
  236. return next;
  237. });
  238. }
  239. function selectAllVisible() {
  240. setSelectedIds((prev) => {
  241. const next = new Set(prev);
  242. for (const s of visibleSpools) next.add(s.id);
  243. return next;
  244. });
  245. }
  246. function deselectVisible() {
  247. setSelectedIds((prev) => {
  248. const next = new Set(prev);
  249. for (const s of visibleSpools) next.delete(s.id);
  250. return next;
  251. });
  252. }
  253. function clearAll() {
  254. setSelectedIds(new Set());
  255. }
  256. async function handlePick(template: SpoolLabelTemplate) {
  257. if (noSelection || pending) return;
  258. const sheetCapacity = SHEET_CAPACITIES[template];
  259. if (
  260. sheetCapacity !== undefined &&
  261. (!startingPositionIsValid || startingPosition > sheetCapacity)
  262. ) {
  263. showToast(
  264. t(
  265. 'inventory.labels.startingPositionRangeError',
  266. 'Starting position must be between 1 and {{capacity}} for this sheet.',
  267. { capacity: sheetCapacity },
  268. ),
  269. 'error',
  270. );
  271. return;
  272. }
  273. // Order matters: the backend (labels.py) prints labels in the same order
  274. // we send IDs. Use the sorted list so a "by colour" sort flows through to
  275. // the PDF instead of being clobbered by an ascending-ID re-sort.
  276. const ids = sortedSpools.filter((s) => selectedIds.has(s.id)).map((s) => s.id);
  277. setPending(template);
  278. try {
  279. const blob = spoolmanMode
  280. ? await api.printSpoolmanSpoolLabels({
  281. spool_ids: ids,
  282. template,
  283. monochrome,
  284. starting_position: sheetCapacity === undefined ? 1 : startingPosition,
  285. })
  286. : await api.printSpoolLabels({
  287. spool_ids: ids,
  288. template,
  289. monochrome,
  290. starting_position: sheetCapacity === undefined ? 1 : startingPosition,
  291. });
  292. openBlobInNewTab(blob);
  293. onClose();
  294. } catch (err) {
  295. const msg = err instanceof Error ? err.message : String(err);
  296. showToast(
  297. t('inventory.labels.error', 'Could not generate labels: {{msg}}', { msg }),
  298. 'error',
  299. );
  300. } finally {
  301. setPending(null);
  302. }
  303. }
  304. return (
  305. <div className="fixed inset-0 z-50 flex items-start sm:items-center justify-center p-4 overflow-y-auto">
  306. <div
  307. className="absolute inset-0 bg-black/60 backdrop-blur-sm"
  308. onClick={onClose}
  309. />
  310. <div
  311. data-testid="label-template-picker-panel"
  312. className="relative w-full max-w-3xl bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] overflow-clip flex flex-col my-auto"
  313. >
  314. {/* Header */}
  315. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  316. <div className="flex items-center gap-2">
  317. <Printer className="w-5 h-5 text-bambu-green" />
  318. <h2 className="text-lg font-semibold text-white">
  319. {t('inventory.labels.title', 'Print spool labels')}
  320. </h2>
  321. {selectedCount > 0 && (
  322. <span className="text-sm text-bambu-gray">
  323. ({t('inventory.labels.selectedCount', '{{count}} selected', { count: selectedCount })})
  324. </span>
  325. )}
  326. </div>
  327. <button
  328. onClick={onClose}
  329. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  330. aria-label={t('common.close', 'Close')}
  331. >
  332. <X className="w-5 h-5" />
  333. </button>
  334. </div>
  335. {/* Search + material chips */}
  336. <div className="p-4 space-y-2 border-b border-bambu-dark-tertiary">
  337. <div className="relative">
  338. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none" />
  339. <input
  340. type="search"
  341. value={search}
  342. onChange={(e) => setSearch(e.target.value)}
  343. placeholder={t('inventory.labels.searchPlaceholder', 'Search name, brand, or #ID')}
  344. 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"
  345. />
  346. </div>
  347. {materials.length > 1 && (
  348. <div className="flex flex-wrap items-center gap-1.5">
  349. <span className="text-xs text-bambu-gray mr-1">
  350. {t('inventory.labels.filterByMaterial', 'Material:')}
  351. </span>
  352. <button
  353. type="button"
  354. onClick={() => setMaterialFilter('')}
  355. className={`px-2 py-0.5 text-xs rounded-full border transition ${
  356. materialFilter === ''
  357. ? 'bg-bambu-green text-bambu-dark border-bambu-green'
  358. : 'bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray'
  359. }`}
  360. >
  361. {t('inventory.labels.allMaterials', 'All')}
  362. </button>
  363. {materials.map((m) => (
  364. <button
  365. key={m}
  366. type="button"
  367. onClick={() => setMaterialFilter(m)}
  368. className={`px-2 py-0.5 text-xs rounded-full border transition ${
  369. materialFilter === m
  370. ? 'bg-bambu-green text-bambu-dark border-bambu-green'
  371. : 'bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray'
  372. }`}
  373. >
  374. {m}
  375. </button>
  376. ))}
  377. </div>
  378. )}
  379. <div className="flex flex-wrap items-center gap-1.5">
  380. <span className="text-xs text-bambu-gray mr-1">
  381. {t('inventory.labels.sortBy.label')}
  382. </span>
  383. <button
  384. type="button"
  385. onClick={() => setSortMode('id')}
  386. className={`px-2 py-0.5 text-xs rounded-full border transition ${
  387. sortMode === 'id'
  388. ? 'bg-bambu-green text-bambu-dark border-bambu-green'
  389. : 'bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray'
  390. }`}
  391. >
  392. {t('inventory.labels.sortBy.id')}
  393. </button>
  394. <button
  395. type="button"
  396. onClick={() => setSortMode('color')}
  397. className={`px-2 py-0.5 text-xs rounded-full border transition ${
  398. sortMode === 'color'
  399. ? 'bg-bambu-green text-bambu-dark border-bambu-green'
  400. : 'bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray'
  401. }`}
  402. >
  403. {t('inventory.labels.sortBy.color')}
  404. </button>
  405. </div>
  406. </div>
  407. {/* Action bar */}
  408. <div className="px-4 pt-3 pb-2 flex items-center justify-between gap-3 flex-wrap">
  409. <span className="text-sm text-bambu-gray">
  410. {t('inventory.labels.pickSpools', 'Pick which spools to print labels for:')}
  411. </span>
  412. <div className="flex items-center gap-3 text-xs">
  413. <button
  414. type="button"
  415. onClick={allVisibleChecked ? deselectVisible : selectAllVisible}
  416. disabled={visibleSpools.length === 0}
  417. className="text-bambu-green hover:underline disabled:opacity-50 disabled:no-underline disabled:cursor-not-allowed"
  418. >
  419. {allVisibleChecked
  420. ? t('inventory.labels.deselectVisible', 'Deselect visible')
  421. : t('inventory.labels.selectVisible', 'Select all visible ({{count}})', {
  422. count: visibleSpools.length,
  423. })}
  424. </button>
  425. <button
  426. type="button"
  427. onClick={clearAll}
  428. disabled={selectedCount === 0}
  429. className="text-bambu-gray hover:text-white hover:underline disabled:opacity-50 disabled:no-underline disabled:cursor-not-allowed"
  430. >
  431. {t('inventory.labels.clearAll', 'Clear all')}
  432. </button>
  433. </div>
  434. </div>
  435. {/* Spool list */}
  436. <div className="flex-1 overflow-y-auto px-2 pb-2 min-h-0">
  437. {visibleSpools.length === 0 ? (
  438. <div className="text-center text-sm text-bambu-gray py-6">
  439. {sortedSpools.length === 0
  440. ? t('inventory.labels.noSpoolsToShow', 'No spools to show. Adjust your filter and try again.')
  441. : t('inventory.labels.noMatches', 'No spools match the current search or filter.')}
  442. </div>
  443. ) : (
  444. <ul className="space-y-0.5">
  445. {visibleSpools.map((s) => {
  446. const checked = selectedIds.has(s.id);
  447. return (
  448. <li key={s.id}>
  449. <label className="flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary/50 cursor-pointer">
  450. {checked ? (
  451. <CheckSquare className="w-4 h-4 text-bambu-green shrink-0" />
  452. ) : (
  453. <Square className="w-4 h-4 text-bambu-gray shrink-0" />
  454. )}
  455. <input
  456. type="checkbox"
  457. checked={checked}
  458. onChange={() => toggleOne(s.id)}
  459. className="sr-only"
  460. />
  461. <span
  462. className="w-4 h-4 rounded border border-black/20 shrink-0"
  463. style={swatchStyle(s.rgba)}
  464. />
  465. <span className="flex-1 min-w-0 truncate text-sm text-white">
  466. {spoolDisplayName(s)}
  467. </span>
  468. <span className="text-xs font-mono text-bambu-gray shrink-0">
  469. #{s.id}
  470. </span>
  471. </label>
  472. </li>
  473. );
  474. })}
  475. </ul>
  476. )}
  477. </div>
  478. {/* Print options */}
  479. <div className="px-4 pt-2 pb-1 border-t border-bambu-dark-tertiary space-y-2">
  480. <label className="inline-flex items-center gap-2 cursor-pointer select-none">
  481. {monochrome ? (
  482. <CheckSquare className="w-4 h-4 text-bambu-green shrink-0" />
  483. ) : (
  484. <Square className="w-4 h-4 text-bambu-gray shrink-0" />
  485. )}
  486. <input
  487. type="checkbox"
  488. checked={monochrome}
  489. onChange={(e) => setMonochrome(e.target.checked)}
  490. className="sr-only"
  491. />
  492. <span className="text-sm text-white">
  493. {t('inventory.labels.monochrome', 'Monochrome (black & white printer)')}
  494. </span>
  495. <span className="text-xs text-bambu-gray">
  496. {t('inventory.labels.monochromeHint', 'Drops the colour swatch and widens the text')}
  497. </span>
  498. </label>
  499. <div className="flex items-start gap-3">
  500. <label
  501. htmlFor="label-starting-position"
  502. className="text-sm text-white whitespace-nowrap pt-1.5"
  503. >
  504. {t('inventory.labels.startingPosition', 'Starting label position')}
  505. </label>
  506. <input
  507. id="label-starting-position"
  508. data-testid="label-starting-position"
  509. type="number"
  510. min={1}
  511. max={MAX_SHEET_CAPACITY}
  512. step={1}
  513. value={startingPositionInput}
  514. onChange={(event) => setStartingPositionInput(event.target.value)}
  515. aria-describedby="label-starting-position-help"
  516. 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"
  517. />
  518. <div id="label-starting-position-help" className="text-xs text-bambu-gray pt-1.5">
  519. <div>
  520. {t(
  521. 'inventory.labels.startingPositionRange',
  522. 'Sheet templates only: L7160 supports 1–21; 5160 supports 1–30.',
  523. )}
  524. </div>
  525. <div
  526. data-testid="label-starting-position-status"
  527. className={startingPositionIsValid ? '' : 'text-red-400'}
  528. >
  529. {!startingPositionIsValid
  530. ? t(
  531. 'inventory.labels.startingPositionInvalid',
  532. 'Enter a whole number from 1 to {{capacity}}.',
  533. { capacity: MAX_SHEET_CAPACITY },
  534. )
  535. : startingPosition === 1
  536. ? t('inventory.labels.startingPositionFirst', 'Printing starts at position 1.')
  537. : t(
  538. 'inventory.labels.startingPositionSkipped',
  539. 'Positions 1 through {{lastPosition}} will be left blank on the first sheet.',
  540. { lastPosition: startingPosition - 1 },
  541. )}
  542. </div>
  543. </div>
  544. </div>
  545. </div>
  546. {/* Templates — 2x2 grid on >= sm so all 4 plus the Cancel footer fit
  547. inside max-h-[90vh] even when browser chrome eats into the viewport
  548. (#1230). Stacked single column on mobile widths. */}
  549. <div className="px-3 pt-1 pb-2 grid grid-cols-1 sm:grid-cols-2 gap-2">
  550. {TEMPLATE_OPTIONS.map((opt) => {
  551. const isPending = pending === opt.value;
  552. const sheetCapacity = SHEET_CAPACITIES[opt.value];
  553. const startingPositionExceedsSheet =
  554. sheetCapacity !== undefined &&
  555. (!startingPositionIsValid || startingPosition > sheetCapacity);
  556. const label = t(`inventory.labels.templates.${opt.i18nKey}.label`, opt.fallbackLabel);
  557. const hint = startingPositionExceedsSheet
  558. ? t(
  559. 'inventory.labels.startingPositionRangeError',
  560. 'Starting position must be between 1 and {{capacity}} for this sheet.',
  561. { capacity: sheetCapacity },
  562. )
  563. : t(`inventory.labels.templates.${opt.i18nKey}.hint`, opt.fallbackHint);
  564. return (
  565. <button
  566. key={opt.value}
  567. data-testid={`print-labels-${opt.value}`}
  568. disabled={noSelection || pending !== null || startingPositionExceedsSheet}
  569. onClick={() => handlePick(opt.value)}
  570. title={`${label} — ${hint}`}
  571. className="w-full text-left p-2.5 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-green hover:bg-bambu-green/10 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-bambu-dark-tertiary disabled:hover:bg-bambu-dark transition flex items-center gap-3"
  572. >
  573. <div className="flex-1 min-w-0">
  574. <div className="font-medium text-white text-sm truncate">{label}</div>
  575. <div className="text-xs text-bambu-gray mt-0.5 truncate">{hint}</div>
  576. </div>
  577. {isPending && <Loader2 className="w-4 h-4 animate-spin text-bambu-green shrink-0" />}
  578. </button>
  579. );
  580. })}
  581. </div>
  582. <div className="flex justify-end gap-2 px-5 py-2 border-t border-bambu-dark-tertiary">
  583. <Button variant="secondary" onClick={onClose} disabled={pending !== null}>
  584. {t('common.cancel', 'Cancel')}
  585. </Button>
  586. </div>
  587. </div>
  588. </div>
  589. );
  590. }