# Gallery Sort Functionality Implementation Guide

## Overview
This guide explains how to integrate the new sorting functionality that allows users to sort plots by name and creation time.

## Frontend Implementation (Complete ✅)

The frontend implementation is complete and includes:

### 1. Sort Controls UI
- **Name/Time buttons**: Toggle between sorting by filename and creation time
- **Order button**: Toggle between ascending (↑) and descending (↓) order
- **Positioned**: Left side of the controls container, next to view toggle buttons
- **Responsive**: Adapts to mobile layouts

### 2. Keyboard Shortcuts
- `Ctrl+N`: Sort by name
- `Ctrl+M`: Sort by time (modification/creation time)
- `Ctrl+O`: Toggle sort order (ascending/descending)

### 3. Persistence
- Sort preferences are saved to localStorage
- Settings persist across page reloads and navigation

### 4. Tile Sizing
- Grid view now shows ~6 plots per row on desktop (240px minimum width)
- Responsive design maintains usability on mobile devices

## Backend Integration (Required)

To enable time-based sorting, you need to modify your Python gallery generation code:

### 1. Add Creation Time to Plot Items

```python
from pathlib import Path

def add_creation_time_to_items(items, base_path):
    """Add creation time to plot items for sorting functionality."""
    for item in items:
        try:
            # Get creation time from PNG or PDF file
            png_path = None
            pdf_path = None
            
            if 'png_href' in item:
                png_rel_path = item['png_href'].replace('../', '').replace('./', '')
                png_path = Path(base_path) / png_rel_path
            
            if 'pdf_href' in item:
                pdf_rel_path = item['pdf_href'].replace('../', '').replace('./', '')
                pdf_path = Path(base_path) / pdf_rel_path
            
            # Use PNG creation time if available, otherwise PDF
            creation_time = 0
            if png_path and png_path.exists():
                creation_time = int(png_path.stat().st_ctime)
            elif pdf_path and pdf_path.exists():
                creation_time = int(pdf_path.stat().st_ctime)
            
            item['creation_time'] = creation_time
            
        except Exception as e:
            print(f"Warning: Could not get creation time for {item.get('name', 'unknown')}: {e}")
            item['creation_time'] = 0
    
    return items
```

### 2. Integrate into Your Gallery Generation

In your existing gallery generation code, call this function before rendering the template:

```python
# Your existing code that creates the items list
items = generate_plot_items()  # Your existing function

# Add creation times
items = add_creation_time_to_items(items, gallery_base_path)

# Pass to template
template.render(items=items, ...)
```

### 3. Template Data Structure

The template now expects each item to have a `creation_time` field:

```python
item = {
    'name': 'plot_name.png',
    'png_href': './plot_name.png',
    'pdf_href': './plot_name.pdf',
    'creation_time': 1642723200  # Unix timestamp
}
```

## File Locations

### Frontend Files (Ready to use)
- `templates/gallery.html` - Updated with sort controls and data attributes
- `assets/css/view-controls.css` - Styling for sort and view controls  
- `assets/css/view-override.css` - Grid layout with larger tiles
- `assets/js/sort-manager.js` - Sort functionality implementation
- `assets/js/gallery-app.js` - Integration of SortManager
- `assets/js/keyboard-manager.js` - Keyboard shortcuts for sorting

### Backend Integration
- `python/add_creation_time.py` - Example implementation for adding creation times

## Features Summary

### ✅ Completed Features
1. **Larger Grid Tiles**: ~6 plots per row instead of 8
2. **Sort Controls**: Name and time sorting with visual feedback
3. **Sort Order Toggle**: Ascending/descending with visual indicator
4. **Keyboard Shortcuts**: Quick access to all sort functions
5. **Persistence**: Settings saved across sessions
6. **Responsive Design**: Works on all screen sizes
7. **Template Integration**: Data attributes ready for backend

### 🔄 Next Steps (Backend Integration)
1. Modify your Python gallery generation code to include `creation_time`
2. Use the provided `add_creation_time_to_items()` function
3. Test with real plot files to ensure timestamps are correct

## Testing

After backend integration:
1. Navigate to a gallery with multiple plots
2. Click the sort buttons to verify functionality
3. Use keyboard shortcuts to test responsiveness
4. Check that sort order toggles correctly
5. Verify settings persist after page reload

The frontend is fully functional and will work immediately once the backend provides the `creation_time` data.
