feat(handlers): Add GetDevicesData helper and update devices template for SSR

- Add GetDevicesData() to DeviceHandler (returns raw data, not JSON)
- Update devices template signature to accept pre-rendered data
- Add server-side rendering of devices and pending registrations
- Update JavaScript to use location.reload() after CRUD operations
- Remove getDeviceIcon dependency on JavaScript function
- Use templ if/else instead of ternary operators for device status

Preserves all API endpoints and backward compatibility
This commit is contained in:
2026-01-31 22:42:21 -05:00
parent 86eaee5a25
commit b3c0c0c225
2 changed files with 158 additions and 160 deletions
+40
View File
@@ -272,6 +272,46 @@ func (h *DeviceHandler) ListDevices(c echo.Context) error {
}) })
} }
func (h *DeviceHandler) GetDevicesData(c echo.Context) ([]DeviceInfo, error) {
userID := c.Get("user_id").(string)
userUUID, err := uuid.Parse(userID)
if err != nil {
return nil, err
}
pgUserID := pgtype.UUID{Bytes: [16]byte(userUUID), Valid: true}
devices, err := h.db.ListDevicesByUser(c.Request().Context(), pgUserID)
if err != nil {
return nil, err
}
deviceList := make([]DeviceInfo, 0, len(devices))
for _, device := range devices {
syncEnabled := device.SyncEnabled.Bool && device.SyncEnabled.Valid
autoSync := device.AutoSync.Bool && device.AutoSync.Valid
syncFreq := int32(0)
if device.SyncFrequencyMinutes.Valid {
syncFreq = device.SyncFrequencyMinutes.Int32
}
deviceList = append(deviceList, DeviceInfo{
ID: device.ID.Bytes,
DeviceName: device.DeviceName,
DeviceType: device.DeviceType,
LastSync: (*time.Time)(&device.LastSync.Time),
LastSeen: (*time.Time)(&device.LastSeen.Time),
SyncEnabled: syncEnabled,
AutoSync: autoSync,
SyncFrequency: syncFreq,
CreatedAt: device.CreatedAt.Time,
DeviceMetadata: device.DeviceMetadata,
})
}
return deviceList, nil
}
func (h *DeviceHandler) GetDevice(c echo.Context) error { func (h *DeviceHandler) GetDevice(c echo.Context) error {
userID := c.Get("user_id") userID := c.Get("user_id")
if userID == nil { if userID == nil {
+89 -131
View File
@@ -1,6 +1,6 @@
package templates package templates
templ Devices(user User) { templ Devices(user User, devices []DeviceData, pendingRegistrations []PendingRegistrationData) {
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
@@ -31,14 +31,9 @@ templ Devices(user User) {
<!-- Devices Grid --> <!-- Devices Grid -->
<div id="devices-container" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"> <div id="devices-container" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
<!-- Loading state -->
<div id="loading" class="text-center py-16 col-span-full" style="color: var(--text-secondary)">
<div class="loading-spinner mx-auto mb-4"></div>
<p>Loading devices...</p>
</div>
<!-- Empty state --> <!-- Empty state -->
<div id="empty-state" class="hidden text-center py-16 col-span-full" style="color: var(--text-secondary)"> if len(devices) == 0 {
<div id="empty-state" class="text-center py-16 col-span-full" style="color: var(--text-secondary)">
<div class="text-6xl mb-4">📱</div> <div class="text-6xl mb-4">📱</div>
<h3 class="text-xl font-semibold mb-2" style="color: var(--text-primary)">No Devices Yet</h3> <h3 class="text-xl font-semibold mb-2" style="color: var(--text-primary)">No Devices Yet</h3>
<p class="mb-4">Add your reading devices to enable cross-device sync</p> <p class="mb-4">Add your reading devices to enable cross-device sync</p>
@@ -46,16 +41,91 @@ templ Devices(user User) {
Add Your First Device Add Your First Device
</button> </button>
</div> </div>
}
<!-- Devices will be loaded here --> <!-- Devices Grid -->
<div id="devices-grid" class="hidden grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"></div> if len(devices) > 0 {
<div id="devices-grid" class="grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
for _, device := range devices {
<div class="card p-6 rounded-lg border" style="background-color: var(--bg-secondary); border-color: var(--border);">
<div class="flex items-start justify-between mb-4">
<div class="text-4xl">
if device.DeviceType == "koreader" {
📖
} else if device.DeviceType == "kobo" {
📚
} else if device.DeviceType == "web" {
🌐
} else {
📱
}
</div>
<div class="flex space-x-2">
<button onclick="showDeviceSettings('{ device.ID }')" class="p-2 hover:opacity-80 rounded" style="color: var(--text-secondary); background-color: var(--bg-primary);">
⚙️
</button>
</div>
</div>
<h3 class="text-lg font-semibold mb-1" style="color: var(--text-primary)">{ device.DeviceName }</h3>
<p class="text-sm mb-4" style="color: var(--text-secondary)">{ device.DeviceType }</p>
<div class="space-y-2 text-sm">
<div class="flex justify-between">
<span style="color: var(--text-secondary)">Sync Status</span>
if device.SyncEnabled {
<span style="color: var(--accent)"> Enabled</span>
} else {
<span style="color: var(--text-secondary)"> Disabled</span>
}
</div>
<div class="flex justify-between">
<span style="color: var(--text-secondary)">Last Sync</span>
if device.LastSync != "" {
<span style="color: var(--text-primary)">{ device.LastSync }</span>
} else {
<span style="color: var(--text-primary)">Never</span>
}
</div>
<div class="flex justify-between">
<span style="color: var(--text-secondary)">Last Seen</span>
if device.LastSeen != "" {
<span style="color: var(--text-primary)">{ device.LastSeen }</span>
} else {
<span style="color: var(--text-primary)">Never</span>
}
</div>
</div>
</div>
}
</div>
}
</div> </div>
<!-- Pending Registrations Section --> <!-- Pending Registrations -->
<div id="pending-section" class="mt-12 hidden"> if len(pendingRegistrations) > 0 {
<div id="pending-section" class="mt-12">
<h2 class="text-2xl font-bold mb-4" style="color: var(--text-primary)">Pending Device Registrations</h2> <h2 class="text-2xl font-bold mb-4" style="color: var(--text-primary)">Pending Device Registrations</h2>
<div id="pending-devices" class="space-y-4"></div> <div class="space-y-4">
for _, reg := range pendingRegistrations {
<div class="card p-4 rounded-lg border flex items-center justify-between" style="background-color: var(--bg-secondary); border-color: var(--border);">
<div>
<h3 class="font-semibold" style="color: var(--text-primary)">{ reg.DeviceName }</h3>
<p class="text-sm" style="color: var(--text-secondary)">
{ reg.DeviceType } - Expires in { reg.ExpiresAt }
</p>
</div> </div>
<div class="flex space-x-2">
<button onclick="approveDevice('{ reg.RegistrationID }')" class="btn-primary px-4 py-2 rounded-lg text-sm">
Approve
</button>
<button onclick="rejectDevice('{ reg.RegistrationID }')" class="btn-danger px-4 py-2 rounded-lg text-sm">
Reject
</button>
</div>
</div>
}
</div>
</div>
}
<!-- Sync Queue Section --> <!-- Sync Queue Section -->
<div id="sync-queue-section" class="mt-12 hidden"> <div id="sync-queue-section" class="mt-12 hidden">
@@ -185,126 +255,14 @@ templ Devices(user User) {
</div> </div>
<script> <script>
let devices = []; function getDeviceIcon(typeName) {
let pendingRegistrations = [];
function loadDevices() {
fetch('/api/devices', {
headers: { 'Authorization': 'Bearer ' + localStorage.getItem('token') }
})
.then(response => response.json())
.then(data => {
devices = data.devices || [];
renderDevices();
loadPendingRegistrations();
})
.catch(error => {
showToast('Failed to load devices', 'error');
document.getElementById('loading').classList.add('hidden');
});
}
function loadPendingRegistrations() {
fetch('/api/devices/pending', {
headers: { 'Authorization': 'Bearer ' + localStorage.getItem('token') }
})
.then(response => response.json())
.then(data => {
pendingRegistrations = data.pending_registrations || [];
renderPendingRegistrations();
})
.catch(() => {
// Ignore error if endpoint doesn't exist
});
}
function renderDevices() {
const loading = document.getElementById('loading');
const emptyState = document.getElementById('empty-state');
const grid = document.getElementById('devices-grid');
loading.classList.add('hidden');
if (devices.length === 0) {
emptyState.classList.remove('hidden');
grid.classList.add('hidden');
return;
}
emptyState.classList.add('hidden');
grid.classList.remove('hidden');
const deviceIcons = { const deviceIcons = {
'koreader': '📖', 'koreader': '📖',
'kobo': '📚', 'kobo': '📚',
'web': '🌐', 'web': '🌐',
'mobile': '📱' 'mobile': '📱'
}; };
return deviceIcons[typeName] || '📱';
grid.innerHTML = devices.map(device => `
<div class="card p-6 rounded-lg border" style="background-color: var(--bg-secondary); border-color: var(--border);">
<div class="flex items-start justify-between mb-4">
<div class="text-4xl">${deviceIcons[device.device_type] || '📱'}</div>
<div class="flex space-x-2">
<button onclick="showDeviceSettings('${device.id}')" class="p-2 hover:opacity-80 rounded" style="color: var(--text-secondary); background-color: var(--bg-primary);">
⚙️
</button>
</div>
</div>
<h3 class="text-lg font-semibold mb-1" style="color: var(--text-primary)">${device.device_name}</h3>
<p class="text-sm mb-4" style="color: var(--text-secondary)">${device.device_type.toUpperCase()}</p>
<div class="space-y-2 text-sm">
<div class="flex justify-between">
<span style="color: var(--text-secondary)">Sync Status</span>
<span style="color: ${device.sync_enabled ? 'var(--accent)' : 'var(--text-secondary)'}">
${device.sync_enabled ? '✓ Enabled' : '✗ Disabled'}
</span>
</div>
<div class="flex justify-between">
<span style="color: var(--text-secondary)">Last Sync</span>
<span style="color: var(--text-primary)">
${device.last_sync ? new Date(device.last_sync).toLocaleString() : 'Never'}
</span>
</div>
<div class="flex justify-between">
<span style="color: var(--text-secondary)">Last Seen</span>
<span style="color: var(--text-primary)">
${device.last_seen ? new Date(device.last_seen).toLocaleString() : 'Never'}
</span>
</div>
</div>
</div>
`).join('');
}
function renderPendingRegistrations() {
const section = document.getElementById('pending-section');
const container = document.getElementById('pending-devices');
if (pendingRegistrations.length === 0) {
section.classList.add('hidden');
return;
}
section.classList.remove('hidden');
container.innerHTML = pendingRegistrations.map(reg => `
<div class="card p-4 rounded-lg border flex items-center justify-between" style="background-color: var(--bg-secondary); border-color: var(--border);">
<div>
<h3 class="font-semibold" style="color: var(--text-primary)">${reg.device_name || 'Unknown Device'}</h3>
<p class="text-sm" style="color: var(--text-secondary)">
${reg.device_type.toUpperCase()} - Expires in ${Math.floor((new Date(reg.expires_at) - new Date()) / 60000)} minutes
</p>
</div>
<div class="flex space-x-2">
<button onclick="approveDevice('${reg.registration_id}')" class="btn-primary px-4 py-2 rounded-lg text-sm">
Approve
</button>
<button onclick="rejectDevice('${reg.registration_id}')" class="btn-danger px-4 py-2 rounded-lg text-sm">
Reject
</button>
</div>
</div>
`).join('');
} }
function showAddDeviceModal() { function showAddDeviceModal() {
@@ -384,7 +342,7 @@ templ Devices(user User) {
.then(result => { .then(result => {
showToast('Device settings saved', 'success'); showToast('Device settings saved', 'success');
hideDeviceSettingsModal(); hideDeviceSettingsModal();
loadDevices(); location.reload();
}) })
.catch(error => { .catch(error => {
showToast('Failed to save settings', 'error'); showToast('Failed to save settings', 'error');
@@ -403,7 +361,7 @@ templ Devices(user User) {
if (response.ok) { if (response.ok) {
showToast('Device revoked successfully', 'success'); showToast('Device revoked successfully', 'success');
hideDeviceSettingsModal(); hideDeviceSettingsModal();
loadDevices(); location.reload();
} else { } else {
showToast('Failed to revoke device', 'error'); showToast('Failed to revoke device', 'error');
} }
@@ -421,7 +379,7 @@ templ Devices(user User) {
.then(response => response.json()) .then(response => response.json())
.then(result => { .then(result => {
showToast('Device approved successfully', 'success'); showToast('Device approved successfully', 'success');
loadPendingRegistrations(); location.reload();
}) })
.catch(error => { .catch(error => {
showToast('Failed to approve device', 'error'); showToast('Failed to approve device', 'error');
@@ -436,7 +394,7 @@ templ Devices(user User) {
.then(response => response.json()) .then(response => response.json())
.then(result => { .then(result => {
showToast('Device registration rejected', 'info'); showToast('Device registration rejected', 'info');
loadPendingRegistrations(); location.reload();
}) })
.catch(error => { .catch(error => {
showToast('Failed to reject device', 'error'); showToast('Failed to reject device', 'error');