88 lines
2.5 KiB
TypeScript
88 lines
2.5 KiB
TypeScript
import {
|
|
createContext,
|
|
useCallback,
|
|
useContext,
|
|
useState,
|
|
type ReactNode,
|
|
} from "react";
|
|
|
|
import type {
|
|
CanvasCodeSelection,
|
|
CanvasSelectionState,
|
|
CanvasTextSelection,
|
|
WritingSelection,
|
|
} from "../types/selection";
|
|
|
|
export interface CanvasUIContextValue {
|
|
isChatCollapsed: boolean;
|
|
isEditing: boolean;
|
|
isWebSearchOpen: boolean;
|
|
selection: CanvasSelectionState;
|
|
/** Tiptap editor selection for AI rewrite flow */
|
|
writingSelection: WritingSelection | null;
|
|
setIsChatCollapsed: (v: boolean) => void;
|
|
setIsEditing: (v: boolean) => void;
|
|
setIsWebSearchOpen: (v: boolean) => void;
|
|
/** Set text selection; clears any existing code selection. */
|
|
setTextSelection: (s: CanvasTextSelection | null) => void;
|
|
/** Set code selection; clears any existing text selection. */
|
|
setCodeSelection: (s: CanvasCodeSelection | null) => void;
|
|
clearSelection: () => void;
|
|
setWritingSelection: (s: WritingSelection | null) => void;
|
|
}
|
|
|
|
const EMPTY_SELECTION: CanvasSelectionState = {
|
|
textSelection: null,
|
|
codeSelection: null,
|
|
};
|
|
|
|
const CanvasUIContext = createContext<CanvasUIContextValue | null>(null);
|
|
|
|
export function CanvasUIProvider({ children }: { children: ReactNode }) {
|
|
const [isChatCollapsed, setIsChatCollapsed] = useState(false);
|
|
const [isEditing, setIsEditing] = useState(false);
|
|
const [isWebSearchOpen, setIsWebSearchOpen] = useState(false);
|
|
const [selection, setSelection] =
|
|
useState<CanvasSelectionState>(EMPTY_SELECTION);
|
|
const [writingSelection, setWritingSelection] =
|
|
useState<WritingSelection | null>(null);
|
|
|
|
const setTextSelection = useCallback((s: CanvasTextSelection | null) => {
|
|
setSelection({ textSelection: s, codeSelection: null });
|
|
}, []);
|
|
|
|
const setCodeSelection = useCallback((s: CanvasCodeSelection | null) => {
|
|
setSelection({ textSelection: null, codeSelection: s });
|
|
}, []);
|
|
|
|
return (
|
|
<CanvasUIContext.Provider
|
|
value={{
|
|
isChatCollapsed,
|
|
isEditing,
|
|
isWebSearchOpen,
|
|
selection,
|
|
writingSelection,
|
|
setIsChatCollapsed,
|
|
setIsEditing,
|
|
setIsWebSearchOpen,
|
|
setTextSelection,
|
|
setCodeSelection,
|
|
clearSelection: () => setSelection(EMPTY_SELECTION),
|
|
setWritingSelection,
|
|
}}
|
|
>
|
|
{children}
|
|
</CanvasUIContext.Provider>
|
|
);
|
|
}
|
|
|
|
export function useCanvasUIContext() {
|
|
const ctx = useContext(CanvasUIContext);
|
|
if (!ctx)
|
|
throw new Error(
|
|
"useCanvasUIContext must be used within CanvasUIProvider",
|
|
);
|
|
return ctx;
|
|
}
|