tahamajs/IE / Projects /front /src /context /DraftContext.tsx
tahamajs's picture
download
raw
6.61 kB
// src/context/DraftContext.tsx
import { createContext, useContext, useEffect, useState, useCallback, useRef, ReactNode } from "react";
import { useAuth } from "./AuthContext";
import { useWebSocket } from "./WebSocketContext";
import { useToast } from "./ToastContext";
// ============================================
// Types
// ============================================
interface Draft {
id: string;
type: "article" | "comment" | "project" | "document";
title: string;
content: any;
lastModified: number;
metadata?: Record<string, any>;
}
interface DraftContextValue {
drafts: Draft[];
saveDraft: (draft: Omit<Draft, "id" | "lastModified">) => string;
updateDraft: (id: string, updates: Partial<Draft>) => void;
getDraft: (id: string) => Draft | undefined;
deleteDraft: (id: string) => void;
clearAllDrafts: () => void;
syncDrafts: () => Promise<void>;
hasUnsavedChanges: (draftId: string) => boolean;
autoSave: (type: Draft["type"], title: string, content: any, metadata?: Record<string, any>) => void;
}
// ============================================
// Constants
// ============================================
const STORAGE_KEY = "app_drafts";
const AUTO_SAVE_DELAY = 2000;
// ============================================
// Context
// ============================================
const DraftContext = createContext<DraftContextValue | null>(null);
export function DraftProvider({ children }: { children: ReactNode }) {
const { user } = useAuth();
const { connectionStatus, sendMessageSync } = useWebSocket();
const toast = useToast();
const [drafts, setDrafts] = useState<Draft[]>([]);
const autoSaveTimeouts = useRef<Map<string, NodeJS.Timeout>>(new Map());
// ============================================
// Load Drafts from localStorage
// ============================================
useEffect(() => {
try {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored) {
const parsed = JSON.parse(stored);
if (Array.isArray(parsed)) setDrafts(parsed);
}
} catch (err) {
console.error("Failed to load drafts:", err);
}
}, []);
// ============================================
// Persist Drafts
// ============================================
useEffect(() => {
localStorage.setItem(STORAGE_KEY, JSON.stringify(drafts));
}, [drafts]);
// ============================================
// Save Draft
// ============================================
const saveDraft = useCallback((draft: Omit<Draft, "id" | "lastModified">): string => {
const id = `${draft.type}-${Date.now()}-${Math.random().toString(36).substr(2, 6)}`;
const newDraft: Draft = {
...draft,
id,
lastModified: Date.now(),
};
setDrafts(prev => {
const filtered = prev.filter(d => !(d.type === draft.type && d.title === draft.title));
return [newDraft, ...filtered];
});
return id;
}, []);
// ============================================
// Update Draft
// ============================================
const updateDraft = useCallback((id: string, updates: Partial<Draft>) => {
setDrafts(prev =>
prev.map(draft =>
draft.id === id ? { ...draft, ...updates, lastModified: Date.now() } : draft
)
);
}, []);
// ============================================
// Get Draft
// ============================================
const getDraft = useCallback((id: string) => drafts.find(d => d.id === id), [drafts]);
// ============================================
// Delete Draft
// ============================================
const deleteDraft = useCallback((id: string) => {
setDrafts(prev => prev.filter(d => d.id !== id));
if (autoSaveTimeouts.current.has(id)) {
clearTimeout(autoSaveTimeouts.current.get(id)!);
autoSaveTimeouts.current.delete(id);
}
}, []);
const clearAllDrafts = useCallback(() => {
setDrafts([]);
for (const timeout of autoSaveTimeouts.current.values()) {
clearTimeout(timeout);
}
autoSaveTimeouts.current.clear();
}, []);
// ============================================
// Sync Drafts
// ============================================
const syncDrafts = useCallback(async () => {
if (connectionStatus !== "connected") {
toast.warning("Cannot sync drafts while offline");
return;
}
if (drafts.length === 0) {
toast.info("No drafts to sync");
return;
}
const toastId = toast.loading(`Syncing ${drafts.length} drafts...`);
try {
const response = await sendMessageSync({
type: "sync_drafts",
payload: drafts,
});
if (response?.success) {
clearAllDrafts();
toast.success("Drafts synced successfully");
} else {
throw new Error(response?.error || "Sync failed");
}
} catch (err) {
console.error("Sync failed:", err);
toast.error("Sync failed, will retry later");
} finally {
toast.dismiss(toastId);
}
}, [drafts, connectionStatus, sendMessageSync, clearAllDrafts, toast]);
// ============================================
// Has Unsaved Changes
// ============================================
const hasUnsavedChanges = useCallback((draftId: string) => {
return !!getDraft(draftId);
}, [getDraft]);
// ============================================
// Auto-Save
// ============================================
const autoSave = useCallback(
(type: Draft["type"], title: string, content: any, metadata?: Record<string, any>) => {
// Clear existing timeout for this title
if (autoSaveTimeouts.current.has(title)) {
clearTimeout(autoSaveTimeouts.current.get(title)!);
}
const timeout = setTimeout(() => {
saveDraft({ type, title, content, metadata });
autoSaveTimeouts.current.delete(title);
}, AUTO_SAVE_DELAY);
autoSaveTimeouts.current.set(title, timeout);
},
[saveDraft]
);
// ============================================
// Value
// ============================================
const value: DraftContextValue = {
drafts,
saveDraft,
updateDraft,
getDraft,
deleteDraft,
clearAllDrafts,
syncDrafts,
hasUnsavedChanges,
autoSave,
};
return (
<DraftContext.Provider value={value}>
{children}
</DraftContext.Provider>
);
}
export const useDrafts = () => {
const ctx = useContext(DraftContext);
if (!ctx) throw new Error("useDrafts must be used within DraftProvider");
return ctx;
};

Xet Storage Details

Size:
6.61 kB
·
Xet hash:
dc21f60fd66f09075c1e9138911851e6e219263dd772f1513c527aeb5cbbdc88

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.