Skip to content

fix(theme): preserve collapsed state on page refresh - #2036

Closed
cipchk wants to merge 2 commits into
masterfrom
fix-theme-layout-collapsed-#2630
Closed

fix(theme): preserve collapsed state on page refresh#2036
cipchk wants to merge 2 commits into
masterfrom
fix-theme-layout-collapsed-#2630

Conversation

@cipchk

@cipchk cipchk commented Jun 5, 2026

Copy link
Copy Markdown
Member

close ng-alain/ng-alain#2630

PR Checklist

Please check if your PR fulfills the following requirements:

PR Type

What kind of change does this PR introduce?

[ ] Bugfix
[ ] Feature
[ ] Code style update (formatting, local variables)
[ ] Refactoring (no functional changes, no api changes)
[ ] Build related changes
[ ] CI related changes
[ ] Documentation content changes
[ ] Application (the showcase website) / infrastructure changes
[ ] Other... Please describe:

What is the current behavior?

Issue Number: N/A

What is the new behavior?

Does this PR introduce a breaking change?

[ ] Yes
[ ] No

Other information

@github-actions

github-actions Bot commented Jun 5, 2026

Copy link
Copy Markdown

Preview is ready!

cipchk and others added 2 commits June 5, 2026 16:00
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@cipchk
cipchk force-pushed the fix-theme-layout-collapsed-#2630 branch from b08c17a to dae04f6 Compare June 5, 2026 08:01

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request modifies the LayoutDefaultService to preserve the user's collapsed sidebar preference on desktop page refreshes by only auto-collapsing the sidebar when matching mobile media queries. It also adds a corresponding unit test. The review feedback highlights two important issues: a responsive resize regression where the sidebar will no longer auto-expand when resizing from mobile back to desktop, and potential test pollution in the new unit test due to modifying localStorage without cleanup. Solutions were suggested to use an initialization flag to handle the first check and to wrap the test in a try...finally block for proper cleanup.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines 50 to 56
private checkMedia(value: boolean): void {
this.settings.setLayout('collapsed', value);
// 仅当匹配媒体(移动端)时自动折叠侧边栏
// 不匹配时(桌面端)不应覆盖用户已持久化的 collapsed 偏好
if (value) {
this.settings.setLayout('collapsed', true);
}
}

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.

high

Issue: Responsive Resize Regression

By only setting the collapsed state when value is true (mobile), the sidebar will never auto-expand when the user resizes their browser window from mobile back to desktop. This breaks the expected responsive behavior of the layout.

Solution

We can use a flag (e.g., isFirstCheck) to identify the initial load/refresh. On the first check (initialization), we only auto-collapse if it's mobile and preserve the persisted state if it's desktop. On subsequent checks (resizing), we follow the responsive state normally.

Note: Please also add private isFirstCheck = true; to the class properties of LayoutDefaultService.

  private checkMedia(value: boolean): void {
    if (this.isFirstCheck) {
      this.isFirstCheck = false;
      if (value) {
        this.settings.setLayout('collapsed', true);
      }
      return;
    }
    this.settings.setLayout('collapsed', value);
  }

Comment on lines +43 to +76
it('should preserve collapsed state on page refresh on desktop #2630', () => {
// Simulate page refresh: localStorage already has collapsed=true from user preference
localStorage.setItem('layout', JSON.stringify({ collapsed: true, fixed: true, boxed: false, lang: null }));

// Provide a mock BreakpointObserver that simulates desktop (isMatched returns false)
TestBed.resetTestingModule();
TestBed.configureTestingModule({
imports: [AlainThemeModule],
providers: [
{
provide: BreakpointObserver,
useFactory: () => {
const mock = jasmine.createSpyObj('BreakpointObserver', ['observe', 'isMatched']);
mock.isMatched.and.returnValue(false);
mock.observe.and.returnValue(
new Observable<BreakpointState>(subscriber => {
subscriber.next({ matches: false, breakpoints: {} });
})
);
return mock;
}
}
]
});

const settings = TestBed.inject(SettingsService);
// Before LayoutDefaultService is created, settings should read collapsed=true from localStorage
expect(settings.layout.collapsed).toBe(true);

// LayoutDefaultService constructor calls checkMedia with isMatched=false (desktop)
// It should NOT overwrite the persisted collapsed state
TestBed.inject(LayoutDefaultService);
expect(settings.layout.collapsed).toBe(true);
});

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.

medium

Issue: Test Pollution via LocalStorage

Modifying localStorage in a unit test without cleaning it up can pollute subsequent tests or other test suites, leading to flaky tests.

Solution

Wrap the test logic in a try...finally block to guarantee that localStorage.removeItem('layout') is called even if an assertion fails.

  it('should preserve collapsed state on page refresh on desktop #2630', () => {
    // Simulate page refresh: localStorage already has collapsed=true from user preference
    localStorage.setItem('layout', JSON.stringify({ collapsed: true, fixed: true, boxed: false, lang: null }));

    try {
      // Provide a mock BreakpointObserver that simulates desktop (isMatched returns false)
      TestBed.resetTestingModule();
      TestBed.configureTestingModule({
        imports: [AlainThemeModule],
        providers: [
          {
            provide: BreakpointObserver,
            useFactory: () => {
              const mock = jasmine.createSpyObj('BreakpointObserver', ['observe', 'isMatched']);
              mock.isMatched.and.returnValue(false);
              mock.observe.and.returnValue(
                new Observable<BreakpointState>(subscriber => {
                  subscriber.next({ matches: false, breakpoints: {} });
                })
              );
              return mock;
            }
          }
        ]
      });

      const settings = TestBed.inject(SettingsService);
      // Before LayoutDefaultService is created, settings should read collapsed=true from localStorage
      expect(settings.layout.collapsed).toBe(true);

      // LayoutDefaultService constructor calls checkMedia with isMatched=false (desktop)
      // It should NOT overwrite the persisted collapsed state
      TestBed.inject(LayoutDefaultService);
      expect(settings.layout.collapsed).toBe(true);
    } finally {
      localStorage.removeItem('layout');
    }
  });

@codecov

codecov Bot commented Jun 5, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.13%. Comparing base (4348f5b) to head (dae04f6).

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #2036      +/-   ##
==========================================
- Coverage   95.14%   95.13%   -0.02%     
==========================================
  Files         270      270              
  Lines        8771     8772       +1     
  Branches     1705     1706       +1     
==========================================
  Hits         8345     8345              
  Misses        338      338              
- Partials       88       89       +1     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@cipchk cipchk closed this Jun 5, 2026
@cipchk
cipchk deleted the fix-theme-layout-collapsed-#2630 branch June 5, 2026 08:05
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.

页面刷新时会覆盖用户保存的侧边栏折叠状态

1 participant