Layout.tsx 51 KB

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