Layout.tsx 51 KB

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