fix(refactor): Cleanup components for improved readability and consistency
This commit is contained in:
parent
1228beb59a
commit
1b0c2c59b8
10 changed files with 590 additions and 350 deletions
|
|
@ -1,11 +1,11 @@
|
|||
import { useState, useEffect, useCallback } from 'react';
|
||||
import {
|
||||
Widget,
|
||||
WidgetConfig,
|
||||
DashboardState,
|
||||
import {
|
||||
Widget,
|
||||
WidgetConfig,
|
||||
DashboardState,
|
||||
DashboardConfig,
|
||||
DASHBOARD_STORAGE_KEYS,
|
||||
WidgetCache
|
||||
WidgetCache,
|
||||
} from '@/lib/types';
|
||||
|
||||
// Helper function to request location permission and get user's location
|
||||
|
|
@ -31,7 +31,7 @@ const requestLocationPermission = async (): Promise<string | undefined> => {
|
|||
enableHighAccuracy: true,
|
||||
timeout: 10000, // 10 seconds timeout
|
||||
maximumAge: 300000, // 5 minutes cache
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
} catch (error) {
|
||||
|
|
@ -43,20 +43,28 @@ const requestLocationPermission = async (): Promise<string | undefined> => {
|
|||
// Helper function to replace date/time variables in prompts on the client side
|
||||
const replaceDateTimeVariables = (prompt: string): string => {
|
||||
let processedPrompt = prompt;
|
||||
|
||||
|
||||
// Replace UTC datetime
|
||||
if (processedPrompt.includes('{{current_utc_datetime}}')) {
|
||||
const utcDateTime = new Date().toISOString();
|
||||
processedPrompt = processedPrompt.replace(/\{\{current_utc_datetime\}\}/g, utcDateTime);
|
||||
processedPrompt = processedPrompt.replace(
|
||||
/\{\{current_utc_datetime\}\}/g,
|
||||
utcDateTime,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
// Replace local datetime
|
||||
if (processedPrompt.includes('{{current_local_datetime}}')) {
|
||||
const now = new Date();
|
||||
const localDateTime = new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString();
|
||||
processedPrompt = processedPrompt.replace(/\{\{current_local_datetime\}\}/g, localDateTime);
|
||||
const localDateTime = new Date(
|
||||
now.getTime() - now.getTimezoneOffset() * 60000,
|
||||
).toISOString();
|
||||
processedPrompt = processedPrompt.replace(
|
||||
/\{\{current_local_datetime\}\}/g,
|
||||
localDateTime,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
return processedPrompt;
|
||||
};
|
||||
|
||||
|
|
@ -66,19 +74,19 @@ interface UseDashboardReturn {
|
|||
isLoading: boolean;
|
||||
error: string | null;
|
||||
settings: DashboardConfig['settings'];
|
||||
|
||||
|
||||
// Widget management
|
||||
addWidget: (config: WidgetConfig) => void;
|
||||
updateWidget: (id: string, config: WidgetConfig) => void;
|
||||
deleteWidget: (id: string) => void;
|
||||
refreshWidget: (id: string, forceRefresh?: boolean) => Promise<void>;
|
||||
refreshAllWidgets: () => Promise<void>;
|
||||
|
||||
refreshAllWidgets: (forceRefresh?: boolean) => Promise<void>;
|
||||
|
||||
// Storage management
|
||||
exportDashboard: () => Promise<string>;
|
||||
importDashboard: (configJson: string) => Promise<void>;
|
||||
clearCache: () => void;
|
||||
|
||||
|
||||
// Settings
|
||||
updateSettings: (newSettings: Partial<DashboardConfig['settings']>) => void;
|
||||
}
|
||||
|
|
@ -103,13 +111,19 @@ export const useDashboard = (): UseDashboardReturn => {
|
|||
// Save widgets to localStorage whenever they change (but not on initial load)
|
||||
useEffect(() => {
|
||||
if (!state.isLoading) {
|
||||
localStorage.setItem(DASHBOARD_STORAGE_KEYS.WIDGETS, JSON.stringify(state.widgets));
|
||||
localStorage.setItem(
|
||||
DASHBOARD_STORAGE_KEYS.WIDGETS,
|
||||
JSON.stringify(state.widgets),
|
||||
);
|
||||
}
|
||||
}, [state.widgets, state.isLoading]);
|
||||
|
||||
// Save settings to localStorage whenever they change
|
||||
useEffect(() => {
|
||||
localStorage.setItem(DASHBOARD_STORAGE_KEYS.SETTINGS, JSON.stringify(state.settings));
|
||||
localStorage.setItem(
|
||||
DASHBOARD_STORAGE_KEYS.SETTINGS,
|
||||
JSON.stringify(state.settings),
|
||||
);
|
||||
}, [state.settings]);
|
||||
|
||||
const loadDashboardData = useCallback(() => {
|
||||
|
|
@ -117,23 +131,27 @@ export const useDashboard = (): UseDashboardReturn => {
|
|||
// Load widgets
|
||||
const savedWidgets = localStorage.getItem(DASHBOARD_STORAGE_KEYS.WIDGETS);
|
||||
const widgets: Widget[] = savedWidgets ? JSON.parse(savedWidgets) : [];
|
||||
|
||||
|
||||
// Convert date strings back to Date objects
|
||||
widgets.forEach(widget => {
|
||||
widgets.forEach((widget) => {
|
||||
if (widget.lastUpdated) {
|
||||
widget.lastUpdated = new Date(widget.lastUpdated);
|
||||
}
|
||||
});
|
||||
|
||||
// Load settings
|
||||
const savedSettings = localStorage.getItem(DASHBOARD_STORAGE_KEYS.SETTINGS);
|
||||
const settings = savedSettings ? JSON.parse(savedSettings) : {
|
||||
parallelLoading: true,
|
||||
autoRefresh: false,
|
||||
theme: 'auto',
|
||||
};
|
||||
const savedSettings = localStorage.getItem(
|
||||
DASHBOARD_STORAGE_KEYS.SETTINGS,
|
||||
);
|
||||
const settings = savedSettings
|
||||
? JSON.parse(savedSettings)
|
||||
: {
|
||||
parallelLoading: true,
|
||||
autoRefresh: false,
|
||||
theme: 'auto',
|
||||
};
|
||||
|
||||
setState(prev => ({
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
widgets,
|
||||
settings,
|
||||
|
|
@ -141,7 +159,7 @@ export const useDashboard = (): UseDashboardReturn => {
|
|||
}));
|
||||
} catch (error) {
|
||||
console.error('Error loading dashboard data:', error);
|
||||
setState(prev => ({
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
error: 'Failed to load dashboard data',
|
||||
isLoading: false,
|
||||
|
|
@ -159,27 +177,27 @@ export const useDashboard = (): UseDashboardReturn => {
|
|||
error: null,
|
||||
};
|
||||
|
||||
setState(prev => ({
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
widgets: [...prev.widgets, newWidget],
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const updateWidget = useCallback((id: string, config: WidgetConfig) => {
|
||||
setState(prev => ({
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
widgets: prev.widgets.map(widget =>
|
||||
widgets: prev.widgets.map((widget) =>
|
||||
widget.id === id
|
||||
? { ...widget, ...config, id } // Preserve the ID
|
||||
: widget
|
||||
: widget,
|
||||
),
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const deleteWidget = useCallback((id: string) => {
|
||||
setState(prev => ({
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
widgets: prev.widgets.filter(widget => widget.id !== id),
|
||||
widgets: prev.widgets.filter((widget) => widget.id !== id),
|
||||
}));
|
||||
|
||||
// Also remove from cache
|
||||
|
|
@ -200,143 +218,160 @@ export const useDashboard = (): UseDashboardReturn => {
|
|||
const isWidgetCacheValid = (widget: Widget): boolean => {
|
||||
const cache = getWidgetCache();
|
||||
const cachedData = cache[widget.id];
|
||||
|
||||
|
||||
if (!cachedData) return false;
|
||||
|
||||
|
||||
const now = new Date();
|
||||
const expiresAt = new Date(cachedData.expiresAt);
|
||||
|
||||
|
||||
return now < expiresAt;
|
||||
};
|
||||
|
||||
const getCacheExpiryTime = (widget: Widget): Date => {
|
||||
const now = new Date();
|
||||
const refreshMs = widget.refreshFrequency * (widget.refreshUnit === 'hours' ? 3600000 : 60000);
|
||||
const refreshMs =
|
||||
widget.refreshFrequency *
|
||||
(widget.refreshUnit === 'hours' ? 3600000 : 60000);
|
||||
return new Date(now.getTime() + refreshMs);
|
||||
};
|
||||
|
||||
const refreshWidget = useCallback(async (id: string, forceRefresh: boolean = false) => {
|
||||
const widget = state.widgets.find(w => w.id === id);
|
||||
if (!widget) return;
|
||||
const refreshWidget = useCallback(
|
||||
async (id: string, forceRefresh: boolean = false) => {
|
||||
const widget = state.widgets.find((w) => w.id === id);
|
||||
if (!widget) return;
|
||||
|
||||
// Check cache first (unless forcing refresh)
|
||||
if (!forceRefresh && isWidgetCacheValid(widget)) {
|
||||
const cache = getWidgetCache();
|
||||
const cachedData = cache[widget.id];
|
||||
setState(prev => ({
|
||||
...prev,
|
||||
widgets: prev.widgets.map(w =>
|
||||
w.id === id
|
||||
? { ...w, content: cachedData.content, lastUpdated: new Date(cachedData.lastFetched) }
|
||||
: w
|
||||
),
|
||||
}));
|
||||
return;
|
||||
}
|
||||
|
||||
// Set loading state
|
||||
setState(prev => ({
|
||||
...prev,
|
||||
widgets: prev.widgets.map(w =>
|
||||
w.id === id ? { ...w, isLoading: true, error: null } : w
|
||||
),
|
||||
}));
|
||||
|
||||
try {
|
||||
// Check if prompt uses location variable and request permission if needed
|
||||
let location: string | undefined;
|
||||
if (widget.prompt.includes('{{location}}')) {
|
||||
location = await requestLocationPermission();
|
||||
}
|
||||
|
||||
// Replace date/time variables on the client side
|
||||
const processedPrompt = replaceDateTimeVariables(widget.prompt);
|
||||
|
||||
const response = await fetch('/api/dashboard/process-widget', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
sources: widget.sources,
|
||||
prompt: processedPrompt,
|
||||
provider: widget.provider,
|
||||
model: widget.model,
|
||||
location,
|
||||
}),
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
const now = new Date();
|
||||
|
||||
if (result.success) {
|
||||
// Update widget
|
||||
setState(prev => ({
|
||||
...prev,
|
||||
widgets: prev.widgets.map(w =>
|
||||
w.id === id
|
||||
? {
|
||||
...w,
|
||||
isLoading: false,
|
||||
content: result.content,
|
||||
lastUpdated: now,
|
||||
error: null,
|
||||
}
|
||||
: w
|
||||
),
|
||||
}));
|
||||
|
||||
// Cache the result
|
||||
// Check cache first (unless forcing refresh)
|
||||
if (!forceRefresh && isWidgetCacheValid(widget)) {
|
||||
const cache = getWidgetCache();
|
||||
cache[id] = {
|
||||
content: result.content,
|
||||
lastFetched: now,
|
||||
expiresAt: getCacheExpiryTime(widget),
|
||||
};
|
||||
localStorage.setItem(DASHBOARD_STORAGE_KEYS.CACHE, JSON.stringify(cache));
|
||||
} else {
|
||||
setState(prev => ({
|
||||
const cachedData = cache[widget.id];
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
widgets: prev.widgets.map(w =>
|
||||
widgets: prev.widgets.map((w) =>
|
||||
w.id === id
|
||||
? {
|
||||
...w,
|
||||
content: cachedData.content,
|
||||
lastUpdated: new Date(cachedData.lastFetched),
|
||||
}
|
||||
: w,
|
||||
),
|
||||
}));
|
||||
return;
|
||||
}
|
||||
|
||||
// Set loading state
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
widgets: prev.widgets.map((w) =>
|
||||
w.id === id ? { ...w, isLoading: true, error: null } : w,
|
||||
),
|
||||
}));
|
||||
|
||||
try {
|
||||
// Check if prompt uses location variable and request permission if needed
|
||||
let location: string | undefined;
|
||||
if (widget.prompt.includes('{{location}}')) {
|
||||
location = await requestLocationPermission();
|
||||
}
|
||||
|
||||
// Replace date/time variables on the client side
|
||||
const processedPrompt = replaceDateTimeVariables(widget.prompt);
|
||||
|
||||
const response = await fetch('/api/dashboard/process-widget', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
sources: widget.sources,
|
||||
prompt: processedPrompt,
|
||||
provider: widget.provider,
|
||||
model: widget.model,
|
||||
location,
|
||||
}),
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
const now = new Date();
|
||||
|
||||
if (result.success) {
|
||||
// Update widget
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
widgets: prev.widgets.map((w) =>
|
||||
w.id === id
|
||||
? {
|
||||
...w,
|
||||
isLoading: false,
|
||||
content: result.content,
|
||||
lastUpdated: now,
|
||||
error: null,
|
||||
}
|
||||
: w,
|
||||
),
|
||||
}));
|
||||
|
||||
// Cache the result
|
||||
const cache = getWidgetCache();
|
||||
cache[id] = {
|
||||
content: result.content,
|
||||
lastFetched: now,
|
||||
expiresAt: getCacheExpiryTime(widget),
|
||||
};
|
||||
localStorage.setItem(
|
||||
DASHBOARD_STORAGE_KEYS.CACHE,
|
||||
JSON.stringify(cache),
|
||||
);
|
||||
} else {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
widgets: prev.widgets.map((w) =>
|
||||
w.id === id
|
||||
? {
|
||||
...w,
|
||||
isLoading: false,
|
||||
error: result.error || 'Failed to refresh widget',
|
||||
}
|
||||
: w,
|
||||
),
|
||||
}));
|
||||
}
|
||||
} catch (error) {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
widgets: prev.widgets.map((w) =>
|
||||
w.id === id
|
||||
? {
|
||||
...w,
|
||||
isLoading: false,
|
||||
error: result.error || 'Failed to refresh widget',
|
||||
error: 'Network error: Failed to refresh widget',
|
||||
}
|
||||
: w
|
||||
: w,
|
||||
),
|
||||
}));
|
||||
}
|
||||
} catch (error) {
|
||||
setState(prev => ({
|
||||
...prev,
|
||||
widgets: prev.widgets.map(w =>
|
||||
w.id === id
|
||||
? {
|
||||
...w,
|
||||
isLoading: false,
|
||||
error: 'Network error: Failed to refresh widget',
|
||||
}
|
||||
: w
|
||||
),
|
||||
}));
|
||||
}
|
||||
}, [state.widgets]);
|
||||
},
|
||||
[state.widgets],
|
||||
);
|
||||
|
||||
const refreshAllWidgets = useCallback(async () => {
|
||||
const activeWidgets = state.widgets.filter(w => !w.isLoading);
|
||||
|
||||
if (state.settings.parallelLoading) {
|
||||
// Refresh all widgets in parallel (force refresh)
|
||||
await Promise.all(activeWidgets.map(widget => refreshWidget(widget.id, true)));
|
||||
} else {
|
||||
// Refresh widgets sequentially (force refresh)
|
||||
for (const widget of activeWidgets) {
|
||||
await refreshWidget(widget.id, true);
|
||||
const refreshAllWidgets = useCallback(
|
||||
async (forceRefresh = false) => {
|
||||
const activeWidgets = state.widgets.filter((w) => !w.isLoading);
|
||||
|
||||
if (state.settings.parallelLoading) {
|
||||
// Refresh all widgets in parallel (force refresh)
|
||||
await Promise.all(
|
||||
activeWidgets.map((widget) => refreshWidget(widget.id, forceRefresh)),
|
||||
);
|
||||
} else {
|
||||
// Refresh widgets sequentially (force refresh)
|
||||
for (const widget of activeWidgets) {
|
||||
await refreshWidget(widget.id, forceRefresh);
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [state.widgets, state.settings.parallelLoading, refreshWidget]);
|
||||
},
|
||||
[state.widgets, state.settings.parallelLoading, refreshWidget],
|
||||
);
|
||||
|
||||
const exportDashboard = useCallback(async (): Promise<string> => {
|
||||
const dashboardConfig: DashboardConfig = {
|
||||
|
|
@ -349,45 +384,57 @@ export const useDashboard = (): UseDashboardReturn => {
|
|||
return JSON.stringify(dashboardConfig, null, 2);
|
||||
}, [state.widgets, state.settings]);
|
||||
|
||||
const importDashboard = useCallback(async (configJson: string): Promise<void> => {
|
||||
try {
|
||||
const config: DashboardConfig = JSON.parse(configJson);
|
||||
|
||||
// Validate the config structure
|
||||
if (!config.widgets || !Array.isArray(config.widgets)) {
|
||||
throw new Error('Invalid dashboard configuration: missing or invalid widgets array');
|
||||
const importDashboard = useCallback(
|
||||
async (configJson: string): Promise<void> => {
|
||||
try {
|
||||
const config: DashboardConfig = JSON.parse(configJson);
|
||||
|
||||
// Validate the config structure
|
||||
if (!config.widgets || !Array.isArray(config.widgets)) {
|
||||
throw new Error(
|
||||
'Invalid dashboard configuration: missing or invalid widgets array',
|
||||
);
|
||||
}
|
||||
|
||||
// Process widgets and ensure they have valid IDs
|
||||
const processedWidgets: Widget[] = config.widgets.map((widget) => ({
|
||||
...widget,
|
||||
id:
|
||||
widget.id ||
|
||||
Date.now().toString() + Math.random().toString(36).substr(2, 9),
|
||||
lastUpdated: widget.lastUpdated ? new Date(widget.lastUpdated) : null,
|
||||
isLoading: false,
|
||||
content: widget.content || null,
|
||||
error: null,
|
||||
}));
|
||||
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
widgets: processedWidgets,
|
||||
settings: { ...prev.settings, ...config.settings },
|
||||
}));
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Failed to import dashboard: ${error instanceof Error ? error.message : 'Invalid JSON'}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Process widgets and ensure they have valid IDs
|
||||
const processedWidgets: Widget[] = config.widgets.map(widget => ({
|
||||
...widget,
|
||||
id: widget.id || Date.now().toString() + Math.random().toString(36).substr(2, 9),
|
||||
lastUpdated: widget.lastUpdated ? new Date(widget.lastUpdated) : null,
|
||||
isLoading: false,
|
||||
content: widget.content || null,
|
||||
error: null,
|
||||
}));
|
||||
|
||||
setState(prev => ({
|
||||
...prev,
|
||||
widgets: processedWidgets,
|
||||
settings: { ...prev.settings, ...config.settings },
|
||||
}));
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to import dashboard: ${error instanceof Error ? error.message : 'Invalid JSON'}`);
|
||||
}
|
||||
}, []);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const clearCache = useCallback(() => {
|
||||
localStorage.removeItem(DASHBOARD_STORAGE_KEYS.CACHE);
|
||||
}, []);
|
||||
|
||||
const updateSettings = useCallback((newSettings: Partial<DashboardConfig['settings']>) => {
|
||||
setState(prev => ({
|
||||
...prev,
|
||||
settings: { ...prev.settings, ...newSettings },
|
||||
}));
|
||||
}, []);
|
||||
const updateSettings = useCallback(
|
||||
(newSettings: Partial<DashboardConfig['settings']>) => {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
settings: { ...prev.settings, ...newSettings },
|
||||
}));
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return {
|
||||
// State
|
||||
|
|
@ -395,19 +442,19 @@ export const useDashboard = (): UseDashboardReturn => {
|
|||
isLoading: state.isLoading,
|
||||
error: state.error,
|
||||
settings: state.settings,
|
||||
|
||||
|
||||
// Widget management
|
||||
addWidget,
|
||||
updateWidget,
|
||||
deleteWidget,
|
||||
refreshWidget,
|
||||
refreshAllWidgets,
|
||||
|
||||
|
||||
// Storage management
|
||||
exportDashboard,
|
||||
importDashboard,
|
||||
clearCache,
|
||||
|
||||
|
||||
// Settings
|
||||
updateSettings,
|
||||
};
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue