mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 08:23:34 +00:00
Rework useLocalStorage to use React Query, fix starring projects updates sidebar immediately
This commit is contained in:
6 files changed
+78
-44
No files matched your search
+6
-6
@@ -56,9 +56,9 @@ const fs = new LightningFSAdapter(lightningFS.promises);
|
||||
export function App() {
|
||||
return (
|
||||
<UnheadProvider head={head}>
|
||||
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
|
||||
<FSProvider fs={fs}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
|
||||
<FSProvider fs={fs}>
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<AISettingsProvider>
|
||||
@@ -75,9 +75,9 @@ export function App() {
|
||||
</AISettingsProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</QueryClientProvider>
|
||||
</FSProvider>
|
||||
</AppProvider>
|
||||
</FSProvider>
|
||||
</AppProvider>
|
||||
</QueryClientProvider>
|
||||
</UnheadProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React from 'react';
|
||||
import React, { useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Plus, Folder, GitBranch, Settings, Loader2, ChevronDown, Star } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -10,6 +10,7 @@ import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import type { Project } from '@/lib/ProjectsManager';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
|
||||
interface ProjectItemProps {
|
||||
project: Project;
|
||||
@@ -56,7 +57,7 @@ const ProjectItem: React.FC<ProjectItemProps> = ({ project, isSelected, onSelect
|
||||
|
||||
{/* Star indicator - only shown when favorited */}
|
||||
{isFavorite && (
|
||||
<div className="flex-shrink-0 relative -mr-2">
|
||||
<div className="flex-shrink-0 relative -mr-2 pointer-events-none">
|
||||
<div className="h-6 w-6 flex items-center justify-center">
|
||||
<Star className="h-4 w-4 text-yellow-500 fill-current" />
|
||||
</div>
|
||||
@@ -82,6 +83,7 @@ export function ProjectSidebar({
|
||||
onSelectProject,
|
||||
className
|
||||
}: ProjectSidebarProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const { data: projects = [], isLoading, error } = useProjects();
|
||||
const [favorites] = useLocalStorage<string[]>('project-favorites', []);
|
||||
|
||||
@@ -92,6 +94,10 @@ export function ProjectSidebar({
|
||||
navigate('/');
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
queryClient.invalidateQueries({ queryKey: ['projects'] });
|
||||
}, [favorites, queryClient]);
|
||||
|
||||
if (error) {
|
||||
console.error('Failed to load projects:', error);
|
||||
}
|
||||
@@ -114,7 +120,7 @@ export function ProjectSidebar({
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0 hover:bg-primary/10"
|
||||
className="h-8 w-8 p-0 hover:bg-primary/10 -mr-2"
|
||||
onClick={() => navigate('/settings')}
|
||||
>
|
||||
<Settings className="h-4 w-4 text-primary/60 hover:text-primary" />
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useEffect } from 'react';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
|
||||
/**
|
||||
* Generic hook for managing localStorage state
|
||||
* Generic hook for managing localStorage state using React Query
|
||||
*/
|
||||
export function useLocalStorage<T>(
|
||||
key: string,
|
||||
@@ -10,11 +11,13 @@ export function useLocalStorage<T>(
|
||||
serialize: (value: T) => string;
|
||||
deserialize: (value: string) => T;
|
||||
}
|
||||
) {
|
||||
): readonly [T, (value: T | ((prev: T) => T)) => void] {
|
||||
const serialize = serializer?.serialize || JSON.stringify;
|
||||
const deserialize = serializer?.deserialize || JSON.parse;
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const [state, setState] = useState<T>(() => {
|
||||
const queryFn = () => {
|
||||
try {
|
||||
const item = localStorage.getItem(key);
|
||||
return item ? deserialize(item) : defaultValue;
|
||||
@@ -22,13 +25,22 @@ export function useLocalStorage<T>(
|
||||
console.warn(`Failed to load ${key} from localStorage:`, error);
|
||||
return defaultValue;
|
||||
}
|
||||
};
|
||||
|
||||
const { data: state } = useQuery({
|
||||
queryKey: ['localStorage', key],
|
||||
queryFn,
|
||||
initialData: queryFn,
|
||||
staleTime: Infinity, // localStorage data doesn't become stale
|
||||
gcTime: Infinity, // Keep in cache indefinitely
|
||||
});
|
||||
|
||||
const setValue = (value: T | ((prev: T) => T)) => {
|
||||
try {
|
||||
const valueToStore = value instanceof Function ? value(state) : value;
|
||||
setState(valueToStore);
|
||||
const currentValue = state ?? defaultValue;
|
||||
const valueToStore = value instanceof Function ? value(currentValue) : value;
|
||||
localStorage.setItem(key, serialize(valueToStore));
|
||||
queryClient.setQueryData(['localStorage', key], valueToStore);
|
||||
} catch (error) {
|
||||
console.warn(`Failed to save ${key} to localStorage:`, error);
|
||||
}
|
||||
@@ -39,7 +51,8 @@ export function useLocalStorage<T>(
|
||||
const handleStorageChange = (e: StorageEvent) => {
|
||||
if (e.key === key && e.newValue !== null) {
|
||||
try {
|
||||
setState(deserialize(e.newValue));
|
||||
const newValue = deserialize(e.newValue);
|
||||
queryClient.setQueryData(['localStorage', key], newValue);
|
||||
} catch (error) {
|
||||
console.warn(`Failed to sync ${key} from localStorage:`, error);
|
||||
}
|
||||
@@ -48,7 +61,7 @@ export function useLocalStorage<T>(
|
||||
|
||||
window.addEventListener('storage', handleStorageChange);
|
||||
return () => window.removeEventListener('storage', handleStorageChange);
|
||||
}, [key, deserialize]);
|
||||
}, [key, deserialize, queryClient]);
|
||||
|
||||
return [state, setValue] as const;
|
||||
}
|
||||
@@ -1,9 +1,26 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import React, { type ReactNode } from 'react';
|
||||
import { useProjects } from './useProjects';
|
||||
import type { Project } from '@/lib/ProjectsManager';
|
||||
|
||||
// Create a test wrapper that provides a fresh QueryClient for each test
|
||||
function createTestWrapper() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
mutations: { retry: false },
|
||||
},
|
||||
});
|
||||
|
||||
return ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
{children}
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
// Mock the useProjectsManager hook
|
||||
vi.mock('./useProjectsManager', () => ({
|
||||
useProjectsManager: () => ({
|
||||
@@ -28,27 +45,26 @@ vi.mock('./useProjectsManager', () => ({
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock localStorage for favorites
|
||||
const mockLocalStorage = {
|
||||
getItem: vi.fn(),
|
||||
setItem: vi.fn(),
|
||||
removeItem: vi.fn(),
|
||||
clear: vi.fn(),
|
||||
};
|
||||
|
||||
Object.defineProperty(window, 'localStorage', {
|
||||
value: mockLocalStorage,
|
||||
});
|
||||
// Mock the useLocalStorage hook
|
||||
let mockFavorites: string[] = [];
|
||||
vi.mock('./useLocalStorage', () => ({
|
||||
useLocalStorage: vi.fn((key: string, defaultValue: unknown) => {
|
||||
if (key === 'project-favorites') {
|
||||
return [mockFavorites, vi.fn()];
|
||||
}
|
||||
return [defaultValue, vi.fn()];
|
||||
}),
|
||||
}));
|
||||
|
||||
describe('useProjects', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockLocalStorage.getItem.mockReturnValue('[]');
|
||||
mockFavorites = [];
|
||||
});
|
||||
|
||||
it('should load and return projects', async () => {
|
||||
const { result } = renderHook(() => useProjects(), {
|
||||
wrapper: TestApp,
|
||||
wrapper: createTestWrapper(),
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -60,11 +76,11 @@ describe('useProjects', () => {
|
||||
});
|
||||
|
||||
it('should sort favorites first, then by lastModified', async () => {
|
||||
// Mock favorites to include project-1
|
||||
mockLocalStorage.getItem.mockReturnValue('["project-1"]');
|
||||
// Set favorites to include project-1
|
||||
mockFavorites = ['project-1'];
|
||||
|
||||
const { result } = renderHook(() => useProjects(), {
|
||||
wrapper: TestApp,
|
||||
wrapper: createTestWrapper(),
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -78,11 +94,11 @@ describe('useProjects', () => {
|
||||
});
|
||||
|
||||
it('should handle multiple favorites correctly', async () => {
|
||||
// Mock favorites to include project-1 and project-2
|
||||
mockLocalStorage.getItem.mockReturnValue('["project-1", "project-2"]');
|
||||
// Set favorites to include project-1 and project-2
|
||||
mockFavorites = ['project-1', 'project-2'];
|
||||
|
||||
const { result } = renderHook(() => useProjects(), {
|
||||
wrapper: TestApp,
|
||||
wrapper: createTestWrapper(),
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -24,6 +24,5 @@ export function useProjects() {
|
||||
return b.lastModified.getTime() - a.lastModified.getTime();
|
||||
});
|
||||
},
|
||||
staleTime: 1000 * 60 * 5, // 5 minutes
|
||||
});
|
||||
}
|
||||
@@ -38,9 +38,9 @@ export function TestApp({ children }: TestAppProps) {
|
||||
|
||||
return (
|
||||
<UnheadProvider head={head}>
|
||||
<AppProvider storageKey='test-app-config' defaultConfig={defaultConfig}>
|
||||
<FSProvider fs={fs}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<AppProvider storageKey='test-app-config' defaultConfig={defaultConfig}>
|
||||
<FSProvider fs={fs}>
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<NostrLoginProvider storageKey='test-login'>
|
||||
@@ -54,9 +54,9 @@ export function TestApp({ children }: TestAppProps) {
|
||||
</NostrLoginProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsProvider>
|
||||
</QueryClientProvider>
|
||||
</FSProvider>
|
||||
</AppProvider>
|
||||
</FSProvider>
|
||||
</AppProvider>
|
||||
</QueryClientProvider>
|
||||
</UnheadProvider>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user