Layout.tsx 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114
  1. import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
  2. import { NavLink, Outlet, useNavigate, useLocation } from 'react-router-dom';
  3. import { Printer, Archive, ListOrdered, BarChart3, Cloud, Settings, Sun, Moon, Monitor, ChevronLeft, ChevronRight, Keyboard, Github, ArrowUpCircle, Wrench, FolderKanban, FolderOpen, X, Menu, Info, Plug, Bug, LogOut, Key, Loader2, Disc3, ShieldAlert, Globe, Bell, type LucideIcon } from 'lucide-react';
  4. import { useTranslation } from 'react-i18next';
  5. import { useTheme } from '../contexts/ThemeContext';
  6. import { KeyboardShortcutsModal } from './KeyboardShortcutsModal';
  7. import { InstallAppButton } from './InstallAppButton';
  8. import { SwitchbarPopover } from './SwitchbarPopover';
  9. import { useQuery, useQueries } from '@tanstack/react-query';
  10. import { api, supportApi, pendingUploadsApi, type Permission } from '../api/client';
  11. import { getIconByName } from './IconPicker';
  12. import { useIsSidebarCompact } from '../hooks/useIsSidebarCompact';
  13. import { useColorCatalogVersion } from '../hooks/useColorCatalogVersion';
  14. import { useSponsorPrompt } from '../hooks/useSponsorPrompt';
  15. import { useUnknownTagPrompt } from '../hooks/useUnknownTagPrompt';
  16. import { UnknownSpoolModal } from './UnknownSpoolModal';
  17. import { useAuth } from '../contexts/AuthContext';
  18. import { useToast } from '../contexts/ToastContext';
  19. import { Card, CardHeader, CardContent } from './Card';
  20. import { parseUTCDate } from '../utils/date';
  21. import { Button } from './Button';
  22. import { BugReportBubble } from './BugReportBubble';
  23. import {
  24. getHiddenSidebarSystemItemIds,
  25. getSidebarOrder,
  26. isExternalSidebarItemId,
  27. saveHiddenSidebarSystemItemIds,
  28. saveSidebarOrder,
  29. SIDEBAR_LAYOUT_CHANGED_EVENT,
  30. } from '../utils/sidebarLayout';
  31. interface NavItem {
  32. id: string;
  33. to: string;
  34. icon: LucideIcon;
  35. labelKey: string; // Translation key
  36. }
  37. export const defaultNavItems: NavItem[] = [
  38. { id: 'printers', to: '/', icon: Printer, labelKey: 'nav.printers' },
  39. { id: 'inventory', to: '/inventory', icon: Disc3, labelKey: 'nav.inventory' },
  40. { id: 'archives', to: '/archives', icon: Archive, labelKey: 'nav.archives' },
  41. { id: 'queue', to: '/queue', icon: ListOrdered, labelKey: 'nav.queue' },
  42. { id: 'projects', to: '/projects', icon: FolderKanban, labelKey: 'nav.projects' },
  43. { id: 'files', to: '/files', icon: FolderOpen, labelKey: 'nav.files' },
  44. { id: 'makerworld', to: '/makerworld', icon: Globe, labelKey: 'nav.makerworld' },
  45. { id: 'profiles', to: '/profiles', icon: Cloud, labelKey: 'nav.profiles' },
  46. { id: 'maintenance', to: '/maintenance', icon: Wrench, labelKey: 'nav.maintenance' },
  47. { id: 'stats', to: '/stats', icon: BarChart3, labelKey: 'nav.stats' },
  48. // User-account feature: gated in isHidden() on advanced auth + user_notifications
  49. // + the notifications:user_email permission. Kept adjacent to Settings
  50. // intentionally. Do not drop this entry — without it the /notifications page
  51. // is orphaned (route + page still exist but no nav link) (#1901).
  52. { id: 'notifications', to: '/notifications', icon: Bell, labelKey: 'nav.notifications' },
  53. { id: 'settings', to: '/settings', icon: Settings, labelKey: 'nav.settings' },
  54. ];
  55. // Get default view from localStorage
  56. export function getDefaultView(): string {
  57. return localStorage.getItem('defaultView') || '/';
  58. }
  59. // Save default view to localStorage
  60. export function setDefaultView(path: string) {
  61. localStorage.setItem('defaultView', path);
  62. }
  63. export function Layout() {
  64. const navigate = useNavigate();
  65. const location = useLocation();
  66. const { mode, resolvedMode, toggleMode } = useTheme();
  67. const { t } = useTranslation();
  68. const isSidebarCompact = useIsSidebarCompact();
  69. // Theme toggle: mode → icon and tooltip
  70. const ThemeIcon = { dark: Sun, light: Monitor, system: Moon }[mode];
  71. const themeSwitchTitle = t({ dark: 'nav.switchToLight', light: 'nav.switchToSystem', system: 'nav.switchToDark' }[mode]);
  72. // Re-render Layout (and the page rendered inside <Outlet />) whenever the
  73. // backend color catalog is (re)populated, so pages that mounted before the
  74. // catalog fetched — and cached HSL-fallback color names during their first
  75. // render — refresh with the real catalog names. See #857.
  76. useColorCatalogVersion();
  77. const { user, authEnabled, logout, hasPermission } = useAuth();
  78. const { showToast } = useToast();
  79. const [showChangePasswordModal, setShowChangePasswordModal] = useState(false);
  80. const [changePasswordData, setChangePasswordData] = useState({ currentPassword: '', newPassword: '', confirmPassword: '' });
  81. const [changePasswordLoading, setChangePasswordLoading] = useState(false);
  82. const [sidebarExpanded, setSidebarExpanded] = useState(() => {
  83. const stored = localStorage.getItem('sidebarExpanded');
  84. return stored !== 'false';
  85. });
  86. const [mobileDrawerOpen, setMobileDrawerOpen] = useState(false);
  87. const [showShortcuts, setShowShortcuts] = useState(false);
  88. const [showSwitchbar, setShowSwitchbar] = useState(false);
  89. const defaultSidebarOrder = useMemo(() => defaultNavItems.map(i => i.id), []);
  90. const [sidebarOrder, setSidebarOrder] = useState<string[]>(() => getSidebarOrder(defaultNavItems.map(i => i.id)));
  91. const [hiddenSystemItemIds, setHiddenSystemItemIds] = useState<string[]>(getHiddenSidebarSystemItemIds);
  92. const hasRedirected = useRef(false);
  93. const [dismissedUpdateVersion, setDismissedUpdateVersion] = useState<string | null>(() =>
  94. sessionStorage.getItem('dismissedUpdateVersion')
  95. );
  96. const [plateDetectionAlert, setPlateDetectionAlert] = useState<{
  97. printer_id: number;
  98. printer_name: string;
  99. message: string;
  100. } | null>(null);
  101. // Check for updates
  102. const { data: versionInfo } = useQuery({
  103. queryKey: ['version'],
  104. queryFn: api.getVersion,
  105. staleTime: Infinity,
  106. });
  107. const { data: settings } = useQuery({
  108. queryKey: ['settings'],
  109. queryFn: api.getSettings,
  110. staleTime: 5 * 60 * 1000, // 5 minutes
  111. });
  112. // Sponsor-prompt toast — fires once per session post-auth if a milestone is eligible.
  113. useSponsorPrompt(settings?.currency ?? 'EUR');
  114. // Unknown-spool prompt — surfaces a confirmation modal when the AMS reports a
  115. // tag with no inventory match (only when `auto_add_unknown_rfid` is off).
  116. const unknownSpool = useUnknownTagPrompt();
  117. // Fetch default sidebar order via a public endpoint (no settings:read needed)
  118. const { data: defaultSidebarData } = useQuery({
  119. queryKey: ['default-sidebar-order'],
  120. queryFn: api.getDefaultSidebarOrder,
  121. staleTime: 5 * 60 * 1000, // 5 minutes
  122. });
  123. // Apply admin default sidebar order once per user (skipped if already applied).
  124. // Uses a per-user localStorage flag to prevent re-application.
  125. useEffect(() => {
  126. const defaultOrder = defaultSidebarData?.default_sidebar_order;
  127. if (!defaultOrder) return;
  128. // Wait for auth state to settle before applying to avoid double-execution
  129. if (authEnabled && !user) return;
  130. const appliedKey = user ? `sidebarDefaultApplied_${user.id}` : 'sidebarDefaultApplied';
  131. if (localStorage.getItem(appliedKey)) return;
  132. try {
  133. const parsed = JSON.parse(defaultOrder);
  134. const orderArr = Array.isArray(parsed) ? parsed : parsed.order;
  135. if (!Array.isArray(orderArr) || orderArr.length === 0) return;
  136. // Filter to valid sidebar item IDs only
  137. const validIds = new Set(defaultNavItems.map(i => i.id));
  138. const filtered = orderArr.filter((id: string) => typeof id === 'string' && (validIds.has(id) || isExternalSidebarItemId(id)));
  139. if (filtered.length > 0) {
  140. setSidebarOrder(filtered);
  141. saveSidebarOrder(filtered);
  142. const hiddenIds = Array.isArray(parsed) ? [] : parsed.hiddenSystemItemIds;
  143. if (Array.isArray(hiddenIds)) {
  144. const filteredHiddenIds = hiddenIds.filter((id: string) => typeof id === 'string' && validIds.has(id) && id !== 'settings');
  145. setHiddenSystemItemIds(filteredHiddenIds);
  146. saveHiddenSidebarSystemItemIds(filteredHiddenIds);
  147. }
  148. localStorage.setItem(appliedKey, '1');
  149. }
  150. } catch (e) {
  151. console.error('Failed to apply default sidebar order:', e);
  152. }
  153. }, [defaultSidebarData?.default_sidebar_order, setSidebarOrder, user, authEnabled]);
  154. // Check advanced auth status — the notifications nav item is gated on it
  155. // (rendered only when authEnabled && advanced_auth_enabled && user_notifications_enabled).
  156. const { data: advancedAuthStatus } = useQuery({
  157. queryKey: ['advancedAuthStatus'],
  158. queryFn: api.getAdvancedAuthStatus,
  159. staleTime: 5 * 60 * 1000, // 5 minutes
  160. enabled: authEnabled,
  161. });
  162. const { data: updateCheck } = useQuery({
  163. queryKey: ['updateCheck'],
  164. queryFn: api.checkForUpdates,
  165. enabled: settings?.check_updates !== false,
  166. staleTime: 60 * 60 * 1000, // 1 hour
  167. refetchInterval: 60 * 60 * 1000, // Check every hour
  168. });
  169. // Fetch external links for sidebar
  170. const { data: externalLinks } = useQuery({
  171. queryKey: ['external-links'],
  172. queryFn: api.getExternalLinks,
  173. });
  174. // Fetch smart plugs to check for switchbar items
  175. const { data: smartPlugs } = useQuery({
  176. queryKey: ['smart-plugs'],
  177. queryFn: api.getSmartPlugs,
  178. staleTime: 30 * 1000, // 30 seconds
  179. });
  180. const hasSwitchbarPlugs = smartPlugs?.some(p => p.show_in_switchbar) ?? false;
  181. // Check debug logging state
  182. const { data: debugLoggingState } = useQuery({
  183. queryKey: ['debugLogging'],
  184. queryFn: supportApi.getDebugLoggingState,
  185. staleTime: 60 * 1000, // 1 minute
  186. refetchInterval: 60 * 1000, // Refresh every minute
  187. });
  188. // Check developer LAN mode warnings
  189. const { data: devModeWarnings } = useQuery({
  190. queryKey: ['developer-mode-warnings'],
  191. queryFn: api.getDeveloperModeWarnings,
  192. staleTime: 10 * 1000,
  193. refetchInterval: 30 * 1000,
  194. refetchOnWindowFocus: true,
  195. });
  196. // Fetch pending queue items count for badge
  197. const { data: queueItems } = useQuery({
  198. queryKey: ['queue', 'pending'],
  199. queryFn: () => api.getQueue(undefined, 'pending'),
  200. staleTime: 5 * 1000, // 5 seconds
  201. refetchInterval: 5 * 1000, // Refresh every 5 seconds
  202. refetchOnWindowFocus: true,
  203. });
  204. const pendingQueueCount = queueItems?.length ?? 0;
  205. // Fetch pending uploads count for archive badge (virtual printer review items)
  206. const { data: pendingUploadsData } = useQuery({
  207. queryKey: ['pending-uploads', 'count'],
  208. queryFn: pendingUploadsApi.getCount,
  209. staleTime: 5 * 1000, // 5 seconds
  210. refetchInterval: 5 * 1000, // Refresh every 5 seconds
  211. refetchOnWindowFocus: true,
  212. });
  213. const pendingUploadsCount = pendingUploadsData?.count ?? 0;
  214. // Check if any printer with pending queue items needs plate clearing
  215. const queuePrinterIds = useMemo(() => {
  216. const ids = new Set<number>();
  217. queueItems?.forEach(item => {
  218. if (item.printer_id) ids.add(item.printer_id);
  219. });
  220. return Array.from(ids);
  221. }, [queueItems]);
  222. const printerStatusQueries = useQueries({
  223. queries: queuePrinterIds.map(id => ({
  224. queryKey: ['printerStatus', id],
  225. queryFn: () => api.getPrinterStatus(id),
  226. staleTime: 30 * 1000, // WebSocket keeps this warm
  227. })),
  228. });
  229. const needsClearPlate = printerStatusQueries.some(result => {
  230. const status = result.data;
  231. if (!status) return false;
  232. return !!status.awaiting_plate_clear;
  233. });
  234. // Calculate debug duration client-side for real-time updates
  235. const [debugDuration, setDebugDuration] = useState<number | null>(null);
  236. useEffect(() => {
  237. if (!debugLoggingState?.enabled || !debugLoggingState.enabled_at) {
  238. setDebugDuration(null);
  239. return;
  240. }
  241. const enabledAt = parseUTCDate(debugLoggingState.enabled_at)?.getTime() ?? Date.now();
  242. const updateDuration = () => {
  243. setDebugDuration(Math.floor((Date.now() - enabledAt) / 1000));
  244. };
  245. updateDuration();
  246. const interval = setInterval(updateDuration, 1000);
  247. return () => clearInterval(interval);
  248. }, [debugLoggingState?.enabled, debugLoggingState?.enabled_at]);
  249. // Build the unified sidebar items list - memoized to prevent re-renders
  250. const navItemsMap = useMemo(() => new Map(defaultNavItems.map(item => [item.id, item])), []);
  251. const extLinksMap = useMemo(() => new Map((externalLinks || []).map(link => [`ext-${link.id}`, link])), [externalLinks]);
  252. // Compute the ordered sidebar: include stored order + any new items
  253. // Hide nav items the user doesn't have read permission for
  254. const orderedSidebarIds = (() => {
  255. const result: string[] = [];
  256. const seen = new Set<string>();
  257. // Map nav item IDs to the permission(s) required to see them. Resources
  258. // that ship in three tiers (legacy `*:read` + granular `*:read_own` /
  259. // `*:read_all`) list all three: the default Operators group is seeded
  260. // with `_own` only, so gating on the legacy alone hides the entry from
  261. // every non-admin user even though the underlying API accepts their
  262. // request (#1755).
  263. const navPermissions: Record<string, Permission | Permission[]> = {
  264. archives: ['archives:read', 'archives:read_own', 'archives:read_all'],
  265. queue: ['queue:read', 'queue:read_own', 'queue:read_all'],
  266. stats: 'stats:read',
  267. profiles: 'kprofiles:read',
  268. maintenance: 'maintenance:read',
  269. projects: 'projects:read',
  270. inventory: 'inventory:read',
  271. files: ['library:read', 'library:read_own', 'library:read_all'],
  272. makerworld: 'makerworld:view',
  273. settings: 'settings:read',
  274. // The user-email-preferences API requires notifications:user_email, so
  275. // gate the nav item on the same permission (both default groups —
  276. // Administrators and Operators — hold it). The advanced-auth /
  277. // user_notifications enablement gate is applied separately below.
  278. notifications: 'notifications:user_email',
  279. };
  280. const isHidden = (id: string) => {
  281. // User-toggled hide (#1673) wins first — cheapest check, explicit intent.
  282. if (hiddenSystemItemIds.includes(id)) return true;
  283. // Permission gate accepts Permission | Permission[] so resources with
  284. // granular `*:read_own` / `*:read_all` tiers (default Operators group)
  285. // don't get hidden from users who only hold the granular variant (#1755).
  286. if (authEnabled && id in navPermissions) {
  287. const required = navPermissions[id];
  288. const granted = Array.isArray(required)
  289. ? required.some((p) => hasPermission(p))
  290. : hasPermission(required);
  291. if (!granted) return true;
  292. }
  293. // notifications nav item also requires advanced auth to be enabled and user_notifications_enabled setting
  294. if (id === 'notifications' && (!authEnabled || !advancedAuthStatus?.advanced_auth_enabled || (settings?.user_notifications_enabled === false))) return true;
  295. return false;
  296. };
  297. // Add items in stored order
  298. for (const id of sidebarOrder) {
  299. if (isHidden(id)) continue;
  300. if (navItemsMap.has(id) || extLinksMap.has(id)) {
  301. result.push(id);
  302. seen.add(id);
  303. }
  304. }
  305. // Add any new internal nav items not in stored order
  306. for (const item of defaultNavItems) {
  307. if (isHidden(item.id)) continue;
  308. if (!seen.has(item.id)) {
  309. result.push(item.id);
  310. seen.add(item.id);
  311. }
  312. }
  313. // Add any new external links not in stored order
  314. for (const link of externalLinks || []) {
  315. const extId = `ext-${link.id}`;
  316. if (!seen.has(extId)) {
  317. result.push(extId);
  318. seen.add(extId);
  319. }
  320. }
  321. return result;
  322. })();
  323. // Show update banner if update available and not dismissed for this version.
  324. // Suppressed when running as a Home Assistant addon — HA Supervisor surfaces
  325. // its own update notification in the HA UI, so the in-app banner is duplicate
  326. // noise that links to a page that just says "update via HA."
  327. const showUpdateBanner = updateCheck?.update_available &&
  328. updateCheck.latest_version &&
  329. updateCheck.latest_version !== dismissedUpdateVersion &&
  330. !updateCheck.is_ha_addon;
  331. const dismissUpdateBanner = () => {
  332. if (updateCheck?.latest_version) {
  333. sessionStorage.setItem('dismissedUpdateVersion', updateCheck.latest_version);
  334. setDismissedUpdateVersion(updateCheck.latest_version);
  335. }
  336. };
  337. // Redirect to default view on initial load
  338. useEffect(() => {
  339. if (!hasRedirected.current && location.pathname === '/') {
  340. const defaultView = getDefaultView();
  341. if (defaultView !== '/') {
  342. hasRedirected.current = true;
  343. navigate(defaultView, { replace: true });
  344. }
  345. }
  346. }, [location.pathname, navigate]);
  347. useEffect(() => {
  348. localStorage.setItem('sidebarExpanded', String(sidebarExpanded));
  349. }, [sidebarExpanded]);
  350. useEffect(() => {
  351. const refreshSidebarLayout = () => {
  352. setSidebarOrder(getSidebarOrder(defaultSidebarOrder));
  353. setHiddenSystemItemIds(getHiddenSidebarSystemItemIds());
  354. };
  355. window.addEventListener(SIDEBAR_LAYOUT_CHANGED_EVENT, refreshSidebarLayout);
  356. window.addEventListener('storage', refreshSidebarLayout);
  357. return () => {
  358. window.removeEventListener(SIDEBAR_LAYOUT_CHANGED_EVENT, refreshSidebarLayout);
  359. window.removeEventListener('storage', refreshSidebarLayout);
  360. };
  361. }, [defaultSidebarOrder]);
  362. // Close compact drawer on navigation
  363. useEffect(() => {
  364. if (isSidebarCompact) {
  365. setMobileDrawerOpen(false);
  366. }
  367. }, [location.pathname, isSidebarCompact]);
  368. // Listen for plate detection warnings (objects on plate, print paused)
  369. // Only show to users with printers:control permission
  370. useEffect(() => {
  371. const handlePlateNotEmpty = (event: Event) => {
  372. // Only show alert to users who can control printers
  373. if (!hasPermission('printers:control')) {
  374. return;
  375. }
  376. const detail = (event as CustomEvent).detail;
  377. setPlateDetectionAlert({
  378. printer_id: detail.printer_id,
  379. printer_name: detail.printer_name,
  380. message: detail.message,
  381. });
  382. };
  383. window.addEventListener('plate-not-empty', handlePlateNotEmpty);
  384. return () => window.removeEventListener('plate-not-empty', handlePlateNotEmpty);
  385. }, [hasPermission]);
  386. // Global keyboard shortcuts for navigation
  387. const handleKeyDown = useCallback((e: KeyboardEvent) => {
  388. const target = e.target as HTMLElement;
  389. // Ignore if typing in an input/textarea
  390. if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {
  391. return;
  392. }
  393. // Number keys for navigation (1-9) - follows sidebar order including external links
  394. if (!e.metaKey && !e.ctrlKey && !e.altKey) {
  395. const keyNum = parseInt(e.key);
  396. if (keyNum >= 1 && keyNum <= orderedSidebarIds.length && keyNum <= 9) {
  397. const id = orderedSidebarIds[keyNum - 1];
  398. e.preventDefault();
  399. if (isExternalSidebarItemId(id)) {
  400. // External link
  401. const extLink = extLinksMap.get(id);
  402. if (extLink?.open_in_new_tab) {
  403. window.open(extLink.url, '_blank', 'noopener,noreferrer');
  404. } else {
  405. const linkId = id.replace('ext-', '');
  406. navigate(`/external/${linkId}`);
  407. }
  408. } else {
  409. // Internal nav item
  410. const navItem = navItemsMap.get(id);
  411. if (navItem) {
  412. navigate(navItem.to);
  413. }
  414. }
  415. return;
  416. }
  417. switch (e.key) {
  418. case '?':
  419. e.preventDefault();
  420. setShowShortcuts(true);
  421. break;
  422. case 'Escape':
  423. setShowShortcuts(false);
  424. break;
  425. }
  426. }
  427. }, [navigate, orderedSidebarIds, navItemsMap, extLinksMap]);
  428. useEffect(() => {
  429. document.addEventListener('keydown', handleKeyDown);
  430. return () => document.removeEventListener('keydown', handleKeyDown);
  431. }, [handleKeyDown]);
  432. return (
  433. <div className="flex min-h-screen">
  434. {/* Compact Header */}
  435. {isSidebarCompact && (
  436. <header className="fixed top-0 left-0 right-0 z-40 h-14 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary flex items-center px-4">
  437. <button
  438. onClick={() => setMobileDrawerOpen(true)}
  439. className="p-2 -ml-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors"
  440. aria-label="Open menu"
  441. >
  442. <Menu className="w-6 h-6 text-white" />
  443. </button>
  444. <img
  445. src={resolvedMode === 'dark' ? '/img/bambuddy_logo_dark_transparent.png' : '/img/bambuddy_logo_light.png'}
  446. alt="Bambuddy"
  447. className="h-8 ml-3"
  448. />
  449. </header>
  450. )}
  451. {/* Compact Drawer Backdrop */}
  452. {isSidebarCompact && mobileDrawerOpen && (
  453. <div
  454. className="fixed inset-0 bg-black/60 z-40 transition-opacity"
  455. onClick={() => setMobileDrawerOpen(false)}
  456. />
  457. )}
  458. {/* Sidebar / Mobile Drawer */}
  459. <aside
  460. className={`bg-bambu-dark-secondary border-r border-bambu-dark-tertiary flex flex-col transition-all duration-300 ${
  461. isSidebarCompact
  462. ? `fixed inset-y-0 left-0 z-50 w-72 transform ${mobileDrawerOpen ? 'translate-x-0' : '-translate-x-full'}`
  463. : `fixed inset-y-0 left-0 z-30 ${sidebarExpanded ? 'w-64' : 'w-16'}`
  464. }`}
  465. >
  466. {/* Logo */}
  467. <div className={`border-b border-bambu-dark-tertiary flex items-center justify-center ${isSidebarCompact || sidebarExpanded ? 'p-4' : 'p-2'}`}>
  468. <img
  469. src={resolvedMode === 'dark' ? '/img/bambuddy_logo_dark_transparent.png' : '/img/bambuddy_logo_light.png'}
  470. alt="Bambuddy"
  471. className={isSidebarCompact || sidebarExpanded ? 'h-16 w-auto' : 'h-8 w-8 object-cover object-left'}
  472. />
  473. </div>
  474. {/* Navigation */}
  475. <nav className="flex-1 p-2 overflow-y-auto">
  476. <ul className="space-y-2">
  477. {orderedSidebarIds.map((id) => {
  478. const isExternal = isExternalSidebarItemId(id);
  479. if (isExternal) {
  480. // Render external link
  481. const link = extLinksMap.get(id);
  482. if (!link) return null;
  483. const LinkIcon = link.custom_icon ? null : getIconByName(link.icon);
  484. return (
  485. <li key={id}>
  486. {link.open_in_new_tab ? (
  487. <a
  488. href={link.url}
  489. target="_blank"
  490. rel="noopener noreferrer"
  491. className={`flex items-center ${isSidebarCompact || sidebarExpanded ? 'gap-3 px-4' : 'justify-center px-2'} py-3 rounded-lg transition-colors group text-bambu-gray-light hover:bg-bambu-dark-tertiary hover:text-white`}
  492. title={!isSidebarCompact && !sidebarExpanded ? link.name : undefined}
  493. >
  494. {link.custom_icon ? (
  495. <img
  496. src={api.getExternalLinkIconUrl(link.id)}
  497. alt=""
  498. className="w-5 h-5 flex-shrink-0"
  499. />
  500. ) : (
  501. LinkIcon && <LinkIcon className="w-5 h-5 flex-shrink-0" />
  502. )}
  503. {(isSidebarCompact || sidebarExpanded) && <span>{link.name}</span>}
  504. </a>
  505. ) : (
  506. <NavLink
  507. to={`/external/${link.id}`}
  508. className={({ isActive }) =>
  509. `flex items-center ${isSidebarCompact || sidebarExpanded ? 'gap-3 px-4' : 'justify-center px-2'} py-3 rounded-lg transition-colors group ${
  510. isActive
  511. ? 'bg-bambu-green text-white'
  512. : 'text-bambu-gray-light hover:bg-bambu-dark-tertiary hover:text-white'
  513. }`
  514. }
  515. title={!isSidebarCompact && !sidebarExpanded ? link.name : undefined}
  516. >
  517. {link.custom_icon ? (
  518. <img
  519. src={api.getExternalLinkIconUrl(link.id)}
  520. alt=""
  521. className="w-5 h-5 flex-shrink-0"
  522. />
  523. ) : (
  524. LinkIcon && <LinkIcon className="w-5 h-5 flex-shrink-0" />
  525. )}
  526. {(isSidebarCompact || sidebarExpanded) && <span>{link.name}</span>}
  527. </NavLink>
  528. )}
  529. </li>
  530. );
  531. } else {
  532. // Render internal nav item
  533. const navItem = navItemsMap.get(id);
  534. if (!navItem) return null;
  535. const { to, icon: Icon, labelKey } = navItem;
  536. const showQueueBadge = id === 'queue' && pendingQueueCount > 0;
  537. const showArchiveBadge = id === 'archives' && pendingUploadsCount > 0;
  538. const badgeCount = showQueueBadge ? pendingQueueCount : showArchiveBadge ? pendingUploadsCount : 0;
  539. const showBadge = showQueueBadge || showArchiveBadge;
  540. const showClearPlateDot = id === 'printers' && needsClearPlate;
  541. return (
  542. <li key={id}>
  543. <NavLink
  544. to={to}
  545. className={({ isActive }) =>
  546. `flex items-center ${isSidebarCompact || sidebarExpanded ? 'gap-3 px-4' : 'justify-center px-2'} py-3 rounded-lg transition-colors group ${
  547. isActive
  548. ? 'bg-bambu-green text-white'
  549. : 'text-bambu-gray-light hover:bg-bambu-dark-tertiary hover:text-white'
  550. }`
  551. }
  552. title={!isSidebarCompact && !sidebarExpanded ? t(labelKey) : undefined}
  553. >
  554. <div className="relative">
  555. <Icon className="w-5 h-5 flex-shrink-0" />
  556. {showClearPlateDot && (
  557. <span className="absolute -top-0.5 -right-0.5 w-2.5 h-2.5 bg-yellow-500 rounded-full border-2 border-bambu-dark-secondary" />
  558. )}
  559. {showBadge && (
  560. <span className={`absolute -top-1.5 -right-1.5 min-w-[18px] h-[18px] px-1 flex items-center justify-center text-[10px] font-bold rounded-full ${
  561. showArchiveBadge ? 'bg-blue-500 text-white' : 'bg-yellow-500 text-black'
  562. }`}>
  563. {badgeCount > 99 ? '99+' : badgeCount}
  564. </span>
  565. )}
  566. </div>
  567. {(isSidebarCompact || sidebarExpanded) && <span>{t(labelKey)}</span>}
  568. </NavLink>
  569. </li>
  570. );
  571. }
  572. })}
  573. </ul>
  574. </nav>
  575. {/* Collapse toggle - hide on compact sidebar */}
  576. {!isSidebarCompact && (
  577. <button
  578. onClick={() => setSidebarExpanded(!sidebarExpanded)}
  579. className="p-2 mx-2 mb-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white flex items-center justify-center"
  580. title={sidebarExpanded ? t('nav.collapseSidebar') : t('nav.expandSidebar')}
  581. >
  582. {sidebarExpanded ? (
  583. <ChevronLeft className="w-5 h-5" />
  584. ) : (
  585. <ChevronRight className="w-5 h-5" />
  586. )}
  587. </button>
  588. )}
  589. {/* Footer */}
  590. <div className="flex-shrink-0 p-2 border-t border-bambu-dark-tertiary">
  591. {isSidebarCompact || sidebarExpanded ? (
  592. <div className="flex flex-col gap-2 px-2">
  593. {/* Top row: icons */}
  594. <div className="flex items-center justify-center gap-1 flex-wrap">
  595. {hasSwitchbarPlugs && (
  596. <div className="relative">
  597. <button
  598. onMouseEnter={() => setShowSwitchbar(true)}
  599. className={`p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors ${
  600. showSwitchbar ? 'text-bambu-green' : 'text-bambu-gray-light hover:text-white'
  601. }`}
  602. title={t('nav.smartSwitches', { defaultValue: 'Smart Switches' })}
  603. >
  604. <Plug className="w-5 h-5" />
  605. </button>
  606. {showSwitchbar && (
  607. <SwitchbarPopover onClose={() => setShowSwitchbar(false)} />
  608. )}
  609. </div>
  610. )}
  611. {hasPermission('system:read') ? (
  612. <NavLink
  613. to="/system"
  614. className={({ isActive }) =>
  615. `p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors ${
  616. isActive ? 'text-bambu-green' : 'text-bambu-gray-light hover:text-white'
  617. }`
  618. }
  619. title={t('nav.system')}
  620. >
  621. <Info className="w-5 h-5" />
  622. </NavLink>
  623. ) : (
  624. <span
  625. className="p-2 rounded-lg text-bambu-gray/50 cursor-not-allowed"
  626. title="You do not have permission to view system information"
  627. >
  628. <Info className="w-5 h-5" />
  629. </span>
  630. )}
  631. <InstallAppButton />
  632. <a
  633. href="https://github.com/maziggy/bambuddy"
  634. target="_blank"
  635. rel="noopener noreferrer"
  636. className="p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white"
  637. title={t('nav.viewOnGithub')}
  638. >
  639. <Github className="w-5 h-5" />
  640. </a>
  641. <button
  642. onClick={() => setShowShortcuts(true)}
  643. className="p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white"
  644. title={t('nav.keyboardShortcuts')}
  645. >
  646. <Keyboard className="w-5 h-5" />
  647. </button>
  648. <button
  649. onClick={toggleMode}
  650. className="p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white"
  651. title={themeSwitchTitle}
  652. >
  653. <ThemeIcon className="w-5 h-5" />
  654. </button>
  655. {authEnabled && user && (
  656. <>
  657. <button
  658. onClick={() => setShowChangePasswordModal(true)}
  659. className="p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white"
  660. title={t('changePassword.title')}
  661. >
  662. <Key className="w-5 h-5" />
  663. </button>
  664. <button
  665. onClick={logout}
  666. className="p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white"
  667. title={t('nav.logout', { defaultValue: 'Logout' })}
  668. >
  669. <LogOut className="w-5 h-5" />
  670. </button>
  671. </>
  672. )}
  673. </div>
  674. {/* Bottom row: version */}
  675. <div className="flex items-center justify-center gap-2">
  676. <span className="text-sm text-bambu-gray">v{versionInfo?.version || '...'}</span>
  677. {updateCheck?.update_available && (
  678. <button
  679. onClick={() => navigate('/settings')}
  680. className="flex items-center gap-1 text-xs text-bambu-green hover:text-bambu-green/80 transition-colors"
  681. title={t('nav.updateAvailable', { version: updateCheck.latest_version })}
  682. >
  683. <ArrowUpCircle className="w-4 h-4" />
  684. <span>{t('nav.update')}</span>
  685. </button>
  686. )}
  687. </div>
  688. </div>
  689. ) : (
  690. <div className="flex flex-col items-center gap-1 overflow-y-auto max-h-[50vh]">
  691. {updateCheck?.update_available && (
  692. <button
  693. onClick={() => navigate('/settings')}
  694. className="p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-green hover:text-bambu-green/80"
  695. title={t('nav.updateAvailable', { version: updateCheck.latest_version })}
  696. >
  697. <ArrowUpCircle className="w-5 h-5" />
  698. </button>
  699. )}
  700. {hasSwitchbarPlugs && (
  701. <div className="relative">
  702. <button
  703. onMouseEnter={() => setShowSwitchbar(true)}
  704. className={`p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors ${
  705. showSwitchbar ? 'text-bambu-green' : 'text-bambu-gray-light hover:text-white'
  706. }`}
  707. title={t('nav.smartSwitches', { defaultValue: 'Smart Switches' })}
  708. >
  709. <Plug className="w-5 h-5" />
  710. </button>
  711. {showSwitchbar && (
  712. <SwitchbarPopover onClose={() => setShowSwitchbar(false)} />
  713. )}
  714. </div>
  715. )}
  716. {hasPermission('system:read') ? (
  717. <NavLink
  718. to="/system"
  719. className={({ isActive }) =>
  720. `p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors ${
  721. isActive ? 'text-bambu-green' : 'text-bambu-gray-light hover:text-white'
  722. }`
  723. }
  724. title={t('nav.system')}
  725. >
  726. <Info className="w-5 h-5" />
  727. </NavLink>
  728. ) : (
  729. <span
  730. className="p-2 rounded-lg text-bambu-gray/50 cursor-not-allowed"
  731. title="You do not have permission to view system information"
  732. >
  733. <Info className="w-5 h-5" />
  734. </span>
  735. )}
  736. <InstallAppButton />
  737. <a
  738. href="https://github.com/maziggy/bambuddy"
  739. target="_blank"
  740. rel="noopener noreferrer"
  741. className="p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white"
  742. title={t('nav.viewOnGithub')}
  743. >
  744. <Github className="w-5 h-5" />
  745. </a>
  746. <button
  747. onClick={() => setShowShortcuts(true)}
  748. className="p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white"
  749. title={t('nav.keyboardShortcuts')}
  750. >
  751. <Keyboard className="w-5 h-5" />
  752. </button>
  753. <button
  754. onClick={toggleMode}
  755. className="p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white"
  756. title={themeSwitchTitle}
  757. >
  758. <ThemeIcon className="w-5 h-5" />
  759. </button>
  760. {authEnabled && user && (
  761. <>
  762. <button
  763. onClick={() => setShowChangePasswordModal(true)}
  764. className="p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white"
  765. title={t('changePassword.title')}
  766. >
  767. <Key className="w-5 h-5" />
  768. </button>
  769. <button
  770. onClick={logout}
  771. className="p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white"
  772. title={t('nav.logout', { defaultValue: 'Logout' })}
  773. >
  774. <LogOut className="w-5 h-5" />
  775. </button>
  776. </>
  777. )}
  778. </div>
  779. )}
  780. </div>
  781. </aside>
  782. {/* Main content */}
  783. <main className={`flex-1 bg-bambu-dark overflow-auto transition-all duration-300 ${
  784. isSidebarCompact ? 'mt-14' : sidebarExpanded ? 'ml-64' : 'ml-16'
  785. }`}>
  786. {/* Debug logging indicator */}
  787. {debugLoggingState?.enabled && (
  788. <div className="bg-amber-100 dark:bg-amber-500/20 border-b border-amber-300 dark:border-amber-500/30 px-4 py-2 flex items-center justify-between">
  789. <div className="flex items-center gap-2 text-sm">
  790. <Bug className="w-4 h-4 text-amber-500 animate-pulse" />
  791. <span className="text-amber-800 dark:text-amber-200">
  792. {t('support.debugLoggingActive', { defaultValue: 'Debug logging is active' })}
  793. {debugDuration !== null && (
  794. <span className="text-amber-700/80 dark:text-amber-300/70 ml-2">
  795. ({Math.floor(debugDuration / 60)}m {debugDuration % 60}s)
  796. </span>
  797. )}
  798. </span>
  799. <button
  800. onClick={() => navigate('/system')}
  801. className="text-amber-700 dark:text-amber-400 hover:text-amber-900 dark:hover:text-amber-300 font-medium underline ml-2"
  802. >
  803. {t('support.manageLogs', { defaultValue: 'Manage' })}
  804. </button>
  805. </div>
  806. </div>
  807. )}
  808. {devModeWarnings && devModeWarnings.length > 0 && (
  809. <div className="bg-orange-100 dark:bg-orange-500/20 border-b border-orange-300 dark:border-orange-500/30 px-4 py-2 flex items-center justify-between">
  810. <div className="flex items-center gap-2 text-sm">
  811. <ShieldAlert className="w-4 h-4 text-orange-500" />
  812. <span className="text-orange-800 dark:text-orange-200">
  813. {t('printers.developerModeWarning', {
  814. names: devModeWarnings.map(w => w.name).join(', '),
  815. defaultValue: `Developer LAN mode is not enabled on: ${devModeWarnings.map(w => w.name).join(', ')}. Some features may not work.`
  816. })}
  817. </span>
  818. <a href="https://wiki.bambulab.com/en/knowledge-sharing/enable-developer-mode"
  819. target="_blank" rel="noopener noreferrer"
  820. className="text-orange-700 dark:text-orange-400 hover:text-orange-900 dark:hover:text-orange-300 font-medium underline ml-2">
  821. {t('printers.howToEnable', { defaultValue: 'How to enable' })}
  822. </a>
  823. </div>
  824. </div>
  825. )}
  826. {/* Persistent update banner */}
  827. {showUpdateBanner && (
  828. <div className="bg-bambu-green/20 border-b border-bambu-green/30 px-4 py-2 flex items-center justify-between">
  829. <div className="flex items-center gap-2 text-sm">
  830. <ArrowUpCircle className="w-4 h-4 text-bambu-green" />
  831. <span>
  832. {t('nav.updateAvailableBanner', {
  833. version: updateCheck?.latest_version,
  834. defaultValue: `Version ${updateCheck?.latest_version} is available!`
  835. })}
  836. </span>
  837. <button
  838. onClick={() => navigate('/settings')}
  839. className="text-bambu-green hover:text-bambu-green/80 font-medium underline"
  840. >
  841. {t('nav.viewUpdate', { defaultValue: 'View update' })}
  842. </button>
  843. </div>
  844. <button
  845. onClick={dismissUpdateBanner}
  846. className="p-1 hover:bg-bambu-dark-tertiary rounded transition-colors"
  847. title={t('common.dismiss', { defaultValue: 'Dismiss' })}
  848. >
  849. <X className="w-4 h-4" />
  850. </button>
  851. </div>
  852. )}
  853. <Outlet />
  854. </main>
  855. <UnknownSpoolModal
  856. prompt={unknownSpool.prompt}
  857. isPending={unknownSpool.isPending}
  858. onConfirm={unknownSpool.confirm}
  859. onCancel={unknownSpool.cancel}
  860. />
  861. {/* Keyboard Shortcuts Modal */}
  862. {showShortcuts && (
  863. <KeyboardShortcutsModal
  864. onClose={() => setShowShortcuts(false)}
  865. sidebarItems={orderedSidebarIds.map(id => {
  866. if (isExternalSidebarItemId(id)) {
  867. const extLink = extLinksMap.get(id);
  868. return extLink ? { type: 'external' as const, label: extLink.name } : null;
  869. } else {
  870. const navItem = navItemsMap.get(id);
  871. return navItem ? { type: 'nav' as const, label: navItem.labelKey, labelKey: navItem.labelKey } : null;
  872. }
  873. }).filter(Boolean) as { type: 'nav' | 'external'; label: string; labelKey?: string }[]}
  874. />
  875. )}
  876. {/* Plate Detection Alert Modal */}
  877. {plateDetectionAlert && (
  878. <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-[100] p-4">
  879. <div className="bg-bambu-dark-secondary border-2 border-yellow-500 rounded-xl shadow-2xl max-w-md w-full animate-in fade-in zoom-in duration-200">
  880. <div className="p-6 text-center">
  881. <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-yellow-500/20 flex items-center justify-center">
  882. <svg className="w-10 h-10 text-yellow-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
  883. <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
  884. </svg>
  885. </div>
  886. <h2 className="text-xl font-bold text-yellow-700 dark:text-yellow-400 mb-2">
  887. {t('plateAlert.title')}
  888. </h2>
  889. <p className="text-lg text-white mb-2">
  890. {plateDetectionAlert.printer_name}
  891. </p>
  892. <p className="text-bambu-gray mb-6">
  893. {t('plateAlert.message')}
  894. </p>
  895. <button
  896. onClick={() => setPlateDetectionAlert(null)}
  897. className="w-full py-3 px-6 bg-yellow-500 hover:bg-yellow-600 text-black font-semibold rounded-lg transition-colors"
  898. >
  899. {t('plateAlert.understand')}
  900. </button>
  901. </div>
  902. </div>
  903. </div>
  904. )}
  905. {/* Change Password Modal */}
  906. {showChangePasswordModal && (
  907. <div
  908. className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4"
  909. onClick={() => {
  910. setShowChangePasswordModal(false);
  911. setChangePasswordData({ currentPassword: '', newPassword: '', confirmPassword: '' });
  912. }}
  913. >
  914. <Card
  915. className="w-full max-w-md"
  916. onClick={(e: React.MouseEvent) => e.stopPropagation()}
  917. >
  918. <CardHeader>
  919. <div className="flex items-center justify-between">
  920. <div className="flex items-center gap-2">
  921. <Key className="w-5 h-5 text-bambu-green" />
  922. <h2 className="text-lg font-semibold text-white">{t('changePassword.title')}</h2>
  923. </div>
  924. <Button
  925. variant="ghost"
  926. size="sm"
  927. onClick={() => {
  928. setShowChangePasswordModal(false);
  929. setChangePasswordData({ currentPassword: '', newPassword: '', confirmPassword: '' });
  930. }}
  931. >
  932. <X className="w-5 h-5" />
  933. </Button>
  934. </div>
  935. </CardHeader>
  936. <CardContent>
  937. <div className="space-y-4">
  938. <input
  939. type="text"
  940. name="username"
  941. autoComplete="username"
  942. value={user?.username ?? ''}
  943. readOnly
  944. hidden
  945. aria-hidden="true"
  946. tabIndex={-1}
  947. />
  948. <div>
  949. <label className="block text-sm font-medium text-white mb-2">
  950. {t('changePassword.currentPassword')}
  951. </label>
  952. <input
  953. type="password"
  954. value={changePasswordData.currentPassword}
  955. onChange={(e) => setChangePasswordData({ ...changePasswordData, currentPassword: e.target.value })}
  956. className="w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors"
  957. placeholder={t('changePassword.currentPasswordPlaceholder')}
  958. autoComplete="current-password"
  959. />
  960. </div>
  961. <div>
  962. <label className="block text-sm font-medium text-white mb-2">
  963. {t('changePassword.newPassword')}
  964. </label>
  965. <input
  966. type="password"
  967. value={changePasswordData.newPassword}
  968. onChange={(e) => setChangePasswordData({ ...changePasswordData, newPassword: e.target.value })}
  969. className="w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors"
  970. placeholder={t('changePassword.newPasswordPlaceholder')}
  971. autoComplete="new-password"
  972. minLength={6}
  973. />
  974. </div>
  975. <div>
  976. <label className="block text-sm font-medium text-white mb-2">
  977. {t('changePassword.confirmPassword')}
  978. </label>
  979. <input
  980. type="password"
  981. value={changePasswordData.confirmPassword}
  982. onChange={(e) => setChangePasswordData({ ...changePasswordData, confirmPassword: e.target.value })}
  983. className={`w-full px-4 py-3 bg-bambu-dark-secondary border rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors ${
  984. changePasswordData.confirmPassword && changePasswordData.newPassword !== changePasswordData.confirmPassword
  985. ? 'border-red-500'
  986. : 'border-bambu-dark-tertiary'
  987. }`}
  988. placeholder={t('changePassword.confirmPasswordPlaceholder')}
  989. autoComplete="new-password"
  990. minLength={6}
  991. />
  992. {changePasswordData.confirmPassword && changePasswordData.newPassword !== changePasswordData.confirmPassword && (
  993. <p className="text-red-700 dark:text-red-400 text-xs mt-1">{t('changePassword.passwordsDoNotMatch')}</p>
  994. )}
  995. </div>
  996. </div>
  997. <div className="mt-6 flex justify-end gap-3">
  998. <Button
  999. variant="secondary"
  1000. onClick={() => {
  1001. setShowChangePasswordModal(false);
  1002. setChangePasswordData({ currentPassword: '', newPassword: '', confirmPassword: '' });
  1003. }}
  1004. >
  1005. {t('common.cancel')}
  1006. </Button>
  1007. <Button
  1008. onClick={async () => {
  1009. if (changePasswordData.newPassword !== changePasswordData.confirmPassword) {
  1010. showToast(t('changePassword.passwordsDoNotMatch'), 'error');
  1011. return;
  1012. }
  1013. if (changePasswordData.newPassword.length < 6) {
  1014. showToast(t('changePassword.passwordTooShort'), 'error');
  1015. return;
  1016. }
  1017. setChangePasswordLoading(true);
  1018. try {
  1019. await api.changePassword(changePasswordData.currentPassword, changePasswordData.newPassword);
  1020. showToast(t('changePassword.success'), 'success');
  1021. setShowChangePasswordModal(false);
  1022. setChangePasswordData({ currentPassword: '', newPassword: '', confirmPassword: '' });
  1023. } catch (error: unknown) {
  1024. const message = error instanceof Error ? error.message : t('changePassword.failed');
  1025. showToast(message, 'error');
  1026. } finally {
  1027. setChangePasswordLoading(false);
  1028. }
  1029. }}
  1030. disabled={changePasswordLoading || !changePasswordData.currentPassword || !changePasswordData.newPassword || changePasswordData.newPassword !== changePasswordData.confirmPassword || changePasswordData.newPassword.length < 6}
  1031. >
  1032. {changePasswordLoading ? (
  1033. <>
  1034. <Loader2 className="w-4 h-4 animate-spin" />
  1035. {t('changePassword.changing')}
  1036. </>
  1037. ) : (
  1038. <>
  1039. <Key className="w-4 h-4" />
  1040. {t('changePassword.title')}
  1041. </>
  1042. )}
  1043. </Button>
  1044. </div>
  1045. </CardContent>
  1046. </Card>
  1047. </div>
  1048. )}
  1049. <BugReportBubble />
  1050. </div>
  1051. );
  1052. }