# Sidebar Active Item & Auto-Scroll Feature

**Date**: 2026-01-16 (Continued)
**Feature**: Sidebar navigation enhancements
**Scope**: Admin Portal & Vendor Portal

---

## ✅ Works for Both Admin and Vendor Portals

This feature is **fully compatible** with both portals:
- **Admin Portal** (`__admin__/`)
- **Vendor Portal** (`vendorportal/`)

Both use the same `scripts.js` and `admin-professional.css` files, ensuring consistent behavior.

## Implementation Details

### 1. **Active Item Highlighting**

The sidebar now automatically highlights the current page you're on.

**How it works:**
- When a page loads, JavaScript checks the current URL
- Finds the matching link in the sidebar
- Adds the `active` class to that link
- If the link is inside a collapsed menu (like "Categories" or "Orders"), it automatically expands that menu

**Visual Indicators:**
- Active link has bright orange background (`--am-primary`)
- White left border accent (3px)
- White icon color
- Bold font weight (600)
- Subtle shadow effect

### 2. **Auto-Scroll to Active Item**

The sidebar automatically scrolls to show the active menu item.

**How it works:**
- After highlighting the active item, JavaScript checks if it's visible in the sidebar viewport
- If the active item is out of view (above or below the visible area), the sidebar smoothly scrolls to center it
- Uses 100ms delay to allow collapse animations to complete first
- Smooth scroll behavior for a pleasant user experience

**Code Location:** `__admin__/js/scripts.js` (lines 45-108)

### 3. **Persistent Menu States**

**What's Remembered:**
- ✅ **Sidebar Toggle**: Collapsed or expanded state (uses `localStorage`)
- ✅ **Active Menu**: Current page is always highlighted
- ✅ **Parent Menus**: Automatically expanded if they contain the active page
- ✅ **Page Scroll Position**: Vertical scroll position on the main content area (uses `sessionStorage`)

**Storage Used:**
- `localStorage.getItem('sb|sidebar-toggle')` - Sidebar collapsed/expanded
- `sessionStorage.getItem('scrollPosition')` - Page scroll position
- URL-based matching - Active item (no storage needed, based on current URL)

### 4. **Enhanced Styling**

**CSS Updates** (`admin-professional.css`):

```css
/* Active link */
.sb-sidenav-dark .sb-sidenav-menu .nav-link.active {
    color: #fff;
    background-color: var(--am-primary); /* Orange */
    font-weight: 600;
    border-left-color: #fff; /* 3px white accent */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* Smooth scrolling */
#layoutSidenav_nav {
    scroll-behavior: smooth;
}
```

---

## User Experience Flow

### Example: Navigating to "Insert Product"

1. **User clicks** "Products" → "Add" in sidebar
2. **Page loads** `insert-product.php`
3. **JavaScript executes:**
   - Finds the link matching `insert-product.php`
   - Adds `active` class to "Add" link
   - Expands the "Products" collapse menu
   - Scrolls sidebar to center the "Add" link
4. **User sees:**
   - Orange-highlighted "Add" link with white border
   - "Products" menu expanded
   - Link visible in sidebar viewport

### Example: Page Refresh

1. **User scrolls down** the page (e.g., filling out a form)
2. **User refreshes** the page (F5 or reload button)
3. **On reload:**
   - Sidebar remains in same collapsed/expanded state
   - Active menu item remains highlighted
   - Page scrolls back to previous scroll position
   - Sidebar shows active item

---

## Browser Compatibility

- ✅ **Chrome/Edge**: Full support
- ✅ **Firefox**: Full support
- ✅ **Safari**: Full support
- ✅ **Mobile browsers**: Full support

Uses:
- `localStorage` (widely supported)
- `sessionStorage` (widely supported)
- `scrollIntoView()` with smooth behavior (modern browsers, graceful fallback)
- `requestAnimationFrame()` (modern browsers)

---

## Technical Details

### JavaScript Implementation

**File:** `__admin__/js/scripts.js`

**Key Functions:**
1. **URL Matching**: `window.location.pathname.split('/').pop()`
2. **Link Finding**: `querySelectorAll('.nav-link')` + `getAttribute('href')`
3. **Parent Menu Expansion**: `link.closest('.collapse')` + `classList.add('show')`
4. **Auto-Scroll**: `scrollIntoView({ behavior: 'smooth', block: 'center' })`

**Timing:**
- Executes on `DOMContentLoaded` event
- 100ms delay before scrolling (allows collapse animation)
- Smooth scroll animation (~300ms duration)

### Edge Cases Handled

✅ **Dashboard**: Active when on `dashboard.php` (no parent menu)
✅ **Nested Menus**: Expands parent when active link is inside (e.g., "Orders" → "New Orders")
✅ **Multiple Matches**: First match wins (uses `forEach` with early assignment)
✅ **No Match**: No error, sidebar remains in default state
✅ **Query Parameters**: Matches work even with `?id=123` in URL
✅ **Vendor Portal Absolute Paths**: Handles `/awesome-mall/vendorportal/...` URLs
✅ **Admin Relative Paths**: Handles `insert-product.php` URLs

**URL Matching Strategy:**
- Matches by **filename** (e.g., `dashboard.php`)
- Falls back to **full path** matching for absolute URLs
- Ignores `#` links (collapse toggles)
- Strips query parameters for cleaner matching

---

## Testing Checklist

- [x] Active link highlights correctly
- [x] Parent menus auto-expand
- [x] Sidebar scrolls to active item
- [x] Sidebar toggle state persists
- [x] Page scroll position restored
- [x] Works on all admin pages
- [x] No JavaScript errors in console
- [x] Smooth animations

---

## Future Enhancements (Optional)

- Add keyboard navigation (arrow keys to move between menu items)
- Add visual indicator for expanded menus (arrow rotation animation)
- Add badge counts next to menu items (e.g., "New Orders (5)")
- Add recent pages history in a dropdown
- Add favorites/pinned pages feature

---

**All sidebar features now working perfectly!** ✅
