Skip to content

fix: Optimize sidebar refresh to avoid redundant loading states - #1921

Merged
seefs001 merged 1 commit into
QuantumNous:alphafrom
RedwindA:refactor/improve-sidebar-perf
Sep 30, 2025
Merged

seefs001 merged 1 commit into
QuantumNous:alphafrom
RedwindA:refactor/improve-sidebar-perf

Conversation

@RedwindA

@RedwindA RedwindA commented Sep 29, 2025 •

Copy link
Copy Markdown
Contributor

PR 类型

  • Bug 修复
  • 新功能

PR 是否包含破坏性更新?

  • 是
  • 否

PR 描述

此次修改针对顶部栏和侧边栏刷新后渲染速度过慢的问题。通过在 useSidebar 中记录首次加载状态,仅在必要时展示加载动画,同时为刷新事件带上源标识和跳过骨架屏的标志,避免重复触发加载。另将顶部栏与侧边栏的最小骨架展示时间降至 200ms,提升首屏与刷新时的响应体验。

Summary by CodeRabbit

  • New Features

    • Header and sidebar loading indicators now display for at least 200 ms to reduce flicker.
    • Sidebar refreshes run quietly in the background without showing loaders unless necessary.
  • Bug Fixes

    • More reliable sidebar setup when user settings are missing or invalid; sensible defaults are applied.
    • Prevents redundant/self-triggered refreshes, reducing interruptions during configuration updates.

@coderabbitai

coderabbitai Bot commented Sep 29, 2025 •

Copy link
Copy Markdown
Contributor

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title accurately captures the core change of the pull request by describing the optimization of the sidebar refresh to prevent redundant loading states, which aligns directly with the primary modifications in useSidebar for instance tracking, skip flags, and reduced skeleton timing detailed in the PR.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (7)
web/src/hooks/common/useHeaderBar.js (1)

42-44: Unify the 200 ms minimum as a shared constant

Passing 200 directly is fine; consider extracting a shared constant (e.g., SKELETON_MIN_MS) used here and in SiderBar to keep behavior consistent and tweakable.

- const isLoading = useMinimumLoadingTime(loading, 200);
+ const SKELETON_MIN_MS = 200;
+ const isLoading = useMinimumLoadingTime(loading, SKELETON_MIN_MS);
web/src/components/layout/SiderBar.jsx (1)

61-62: Good alignment with header; consider centralizing the 200 ms value

Looks good and matches the header behavior. Recommend using a shared constant to avoid magic numbers drifting across components.

- const showSkeleton = useMinimumLoadingTime(sidebarLoading, 200);
+ const SKELETON_MIN_MS = 200;
+ const showSkeleton = useMinimumLoadingTime(sidebarLoading, SKELETON_MIN_MS);
web/src/hooks/common/useSidebar.js (5)

24-27: Make EventTarget/CustomEvent usage SSR‑safe

If this hook is imported during SSR, EventTarget/CustomEvent may be missing. Guard creation/usage to avoid ReferenceErrors.

-const sidebarEventTarget = new EventTarget();
+const sidebarEventTarget =
+  typeof window !== 'undefined' && typeof window.EventTarget !== 'undefined'
+    ? new EventTarget()
+    : null;
-    sidebarEventTarget.dispatchEvent(
-      new CustomEvent(SIDEBAR_REFRESH_EVENT, {
-        detail: { sourceId: instanceIdRef.current, skipLoader: true },
-      }),
-    );
+    if (sidebarEventTarget && typeof window !== 'undefined' && typeof window.CustomEvent !== 'undefined') {
+      sidebarEventTarget.dispatchEvent(
+        new CustomEvent(SIDEBAR_REFRESH_EVENT, {
+          detail: { sourceId: instanceIdRef.current, skipLoader: true },
+        }),
+      );
+    }
-    sidebarEventTarget.addEventListener(SIDEBAR_REFRESH_EVENT, handleRefresh);
+    if (sidebarEventTarget) {
+      sidebarEventTarget.addEventListener(SIDEBAR_REFRESH_EVENT, handleRefresh);
+    }
@@
-      sidebarEventTarget.removeEventListener(SIDEBAR_REFRESH_EVENT, handleRefresh);
+      if (sidebarEventTarget) {
+        sidebarEventTarget.removeEventListener(SIDEBAR_REFRESH_EVENT, handleRefresh);
+      }

Also applies to: 153-159, 183-187


84-94: Loader gating logic is sound; document the semantics

withLoading tri‑state is clean: true forces loader, false suppresses, undefined uses first‑load heuristic. Add a brief comment to avoid regressions.


106-124: DRY up default user config construction

The default user config build is duplicated in success and error paths. Extract a helper to reduce drift.

-        const defaultUserConfig = {};
-        Object.keys(adminConfig).forEach((sectionKey) => {
-          if (adminConfig[sectionKey]?.enabled) {
-            defaultUserConfig[sectionKey] = { enabled: true };
-            // 为每个管理员允许的模块设置默认值为true
-            Object.keys(adminConfig[sectionKey]).forEach((moduleKey) => {
-              if (
-                moduleKey !== 'enabled' &&
-                adminConfig[sectionKey][moduleKey]
-              ) {
-                defaultUserConfig[sectionKey][moduleKey] = true;
-              }
-            });
-          }
-        });
-        setUserConfig(defaultUserConfig);
+        setUserConfig(buildDefaultUserConfig(adminConfig));
@@
-      const defaultUserConfig = {};
-      Object.keys(adminConfig).forEach((sectionKey) => {
-        if (adminConfig[sectionKey]?.enabled) {
-          defaultUserConfig[sectionKey] = { enabled: true };
-          Object.keys(adminConfig[sectionKey]).forEach((moduleKey) => {
-            if (moduleKey !== 'enabled' && adminConfig[sectionKey][moduleKey]) {
-              defaultUserConfig[sectionKey][moduleKey] = true;
-            }
-          });
-        }
-      });
-      setUserConfig(defaultUserConfig);
+      setUserConfig(buildDefaultUserConfig(adminConfig));

Add this helper near the defaults:

function buildDefaultUserConfig(adminConfig) {
  const out = {};
  Object.keys(adminConfig).forEach((sectionKey) => {
    if (adminConfig[sectionKey]?.enabled) {
      out[sectionKey] = { enabled: true };
      Object.keys(adminConfig[sectionKey]).forEach((moduleKey) => {
        if (moduleKey !== 'enabled' && adminConfig[sectionKey][moduleKey]) {
          out[sectionKey][moduleKey] = true;
        }
      });
    }
  });
  return out;
}

Also applies to: 126-139


148-159: Stabilize refreshUserConfig identity

Wrap with useCallback to avoid re‑creations and ease passing to children.

-import { useState, useEffect, useMemo, useContext, useRef } from 'react';
+import { useState, useEffect, useMemo, useContext, useRef, useCallback } from 'react';
@@
-  const refreshUserConfig = async () => {
+  const refreshUserConfig = useCallback(async () => {
     if (Object.keys(adminConfig).length > 0) {
       await loadUserConfig({ withLoading: false });
     }
@@
-  };
+  }, [adminConfig]);

95-105: Optional: cancel in‑flight request on unmount

To prevent state updates after unmount during rapid navigations, consider wiring an AbortController (if API.get supports it) and early‑return when aborted.

// Example pattern:
useEffect(() => {
  const ac = new AbortController();
  loadUserConfig({ signal: ac.signal }); // plumb through to API.get
  return () => ac.abort();
}, [adminConfig]);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4bb4b64 and fa45cb5.

📒 Files selected for processing (3)
  • web/src/components/layout/SiderBar.jsx (1 hunks)
  • web/src/hooks/common/useHeaderBar.js (1 hunks)
  • web/src/hooks/common/useSidebar.js (5 hunks)
🔇 Additional comments (1)
web/src/hooks/common/useSidebar.js (1)

171-180: Good self‑origin event filter

Ignoring events from the same instanceId avoids loops; combined with skipLoader this achieves the PR goal of no redundant skeletons on cross‑instance refresh.

Please sanity‑check that a manual refresh from one tab updates another tab’s sidebar without showing the skeleton there, while the originating tab also avoids a skeleton.

@seefs001
seefs001 changed the base branch from main to alpha September 30, 2025 01:38
@seefs001
seefs001 merged commit 7d7ffc0 into QuantumNous:alpha Sep 30, 2025
x22x22 pushed a commit to x22x22/new-api that referenced this pull request Apr 24, 2026
…debar-perf

fix: Optimize sidebar refresh to avoid redundant loading states
@RedwindA
RedwindA deleted the refactor/improve-sidebar-perf branch July 23, 2026 07:04
salem-2007 added a commit to salem-2007/new-api that referenced this pull request Sep 10, 2026
…debar-perf

fix: Optimize sidebar refresh to avoid redundant loading states
junjundesk pushed a commit to junjundesk/new-api that referenced this pull request Oct 3, 2026
…debar-perf

fix: Optimize sidebar refresh to avoid redundant loading states
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants