tahamajs/IE / Projects /front /src /hooks /useContextMenu.tsx
tahamajs's picture
download
raw
11.5 kB
// src/hooks/useContextMenu.tsx
import { useState, useCallback, useRef, useEffect, ReactNode } from "react";
import { ContextMenuItem } from "@/components/ui/ContextMenu";
export interface ContextMenuState {
visible: boolean;
position: { x: number; y: number };
items: ContextMenuItem[];
data?: any;
}
export interface UseContextMenuOptions {
closeOnScroll?: boolean;
closeOnResize?: boolean;
closeOnClickOutside?: boolean;
disableRightClick?: boolean;
customEvent?: string;
}
export function useContextMenu(options: UseContextMenuOptions = {}) {
const {
closeOnScroll = true,
closeOnResize = true,
closeOnClickOutside = true,
disableRightClick = false,
customEvent,
} = options;
const [contextMenu, setContextMenu] = useState<ContextMenuState>({
visible: false,
position: { x: 0, y: 0 },
items: [],
data: null,
});
const elementRef = useRef<HTMLElement | null>(null);
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
const showContextMenu = useCallback((
e: React.MouseEvent | MouseEvent,
items: ContextMenuItem[],
data?: any
) => {
e.preventDefault();
e.stopPropagation();
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
setContextMenu({
visible: true,
position: { x: e.clientX, y: e.clientY },
items,
data,
});
}, []);
const showContextMenuAtPosition = useCallback((
position: { x: number; y: number },
items: ContextMenuItem[],
data?: any
) => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
setContextMenu({
visible: true,
position,
items,
data,
});
}, []);
const hideContextMenu = useCallback(() => {
timeoutRef.current = setTimeout(() => {
setContextMenu(prev => ({ ...prev, visible: false, data: null }));
timeoutRef.current = null;
}, 50);
}, []);
const hideContextMenuImmediately = useCallback(() => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
setContextMenu(prev => ({ ...prev, visible: false, data: null }));
}, []);
// Handle click outside
useEffect(() => {
if (!closeOnClickOutside) return;
const handleClickOutside = (e: MouseEvent) => {
const target = e.target as HTMLElement;
if (contextMenu.visible && !target.closest(".context-menu")) {
hideContextMenuImmediately();
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, [contextMenu.visible, closeOnClickOutside, hideContextMenuImmediately]);
// Handle scroll
useEffect(() => {
if (!closeOnScroll) return;
const handleScroll = () => {
if (contextMenu.visible) {
hideContextMenuImmediately();
}
};
window.addEventListener("scroll", handleScroll, true);
return () => window.removeEventListener("scroll", handleScroll, true);
}, [contextMenu.visible, closeOnScroll, hideContextMenuImmediately]);
// Handle resize
useEffect(() => {
if (!closeOnResize) return;
const handleResize = () => {
if (contextMenu.visible) {
hideContextMenuImmediately();
}
};
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, [contextMenu.visible, closeOnResize, hideContextMenuImmediately]);
// Attach context menu listener to element
const attachToElement = useCallback((
element: HTMLElement | null,
items: ContextMenuItem[] | ((data?: any) => ContextMenuItem[]),
getData?: () => any
) => {
elementRef.current = element;
if (element) {
const handler = (e: MouseEvent) => {
if (disableRightClick) return;
e.preventDefault();
e.stopPropagation();
const menuItems = typeof items === "function"
? items(getData?.())
: items;
showContextMenu(e, menuItems, getData?.());
};
element.addEventListener("contextmenu", handler);
(element as any)._contextMenuHandler = handler;
}
return () => {
if (elementRef.current) {
elementRef.current.removeEventListener("contextmenu", (elementRef.current as any)._contextMenuHandler);
}
};
}, [disableRightClick, showContextMenu]);
// Detach from element
const detach = useCallback(() => {
if (elementRef.current) {
elementRef.current.removeEventListener("contextmenu", (elementRef.current as any)._contextMenuHandler);
elementRef.current = null;
}
}, []);
// Handle custom events
useEffect(() => {
if (!customEvent) return;
const handleCustomEvent = (e: CustomEvent) => {
showContextMenuAtPosition(e.detail.position, e.detail.items, e.detail.data);
};
window.addEventListener(customEvent, handleCustomEvent as any);
return () => window.removeEventListener(customEvent, handleCustomEvent as any);
}, [customEvent, showContextMenuAtPosition]);
// Cleanup on unmount
useEffect(() => {
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
detach();
};
}, [detach]);
return {
contextMenu,
showContextMenu,
showContextMenuAtPosition,
hideContextMenu,
hideContextMenuImmediately,
attachToElement,
detach,
isVisible: contextMenu.visible,
currentItems: contextMenu.items,
currentData: contextMenu.data,
};
}
// Helper function to copy text to clipboard
export const copyToClipboard = (text: string) => {
navigator.clipboard.writeText(text);
};
// Helper function to select all text
export const selectAllText = () => {
const selection = window.getSelection();
if (selection) {
selection.selectAllChildren(document.body);
}
};
// Helper function to download image
export const downloadImage = (url: string) => {
const a = document.createElement("a");
a.href = url;
a.download = url.split("/").pop() || "image";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
};
// Helper function to copy image to clipboard
export const copyImageToClipboard = async (url: string) => {
try {
const response = await fetch(url);
const blob = await response.blob();
await navigator.clipboard.write([
new ClipboardItem({
[blob.type]: blob,
}),
]);
} catch (error) {
console.error("Failed to copy image:", error);
}
};
// Helper function to create standard context menu items (without JSX to avoid issues)
export const createStandardMenuItems = {
forText: (text: string, onCopy?: () => void, onCut?: () => void, onPaste?: () => void): ContextMenuItem[] => [
{ label: "Copy", onClick: () => onCopy?.() || copyToClipboard(text), shortcut: "Ctrl+C" },
{ label: "Cut", onClick: () => onCut?.(), shortcut: "Ctrl+X", disabled: !onCut },
{ label: "Paste", onClick: () => onPaste?.(), shortcut: "Ctrl+V", disabled: !onPaste },
{ divider: true },
{ label: "Select All", onClick: () => selectAllText(), shortcut: "Ctrl+A" },
],
forLink: (url: string, onOpen?: () => void, onCopy?: () => void): ContextMenuItem[] => [
{ label: "Open Link", onClick: () => onOpen?.() || window.open(url, "_blank") },
{ label: "Copy Link", onClick: () => onCopy?.() || copyToClipboard(url) },
{ divider: true },
{ label: "Share", onClick: () => navigator.share?.({ url }) },
],
forImage: (imageUrl: string, onSave?: () => void, onCopy?: () => void): ContextMenuItem[] => [
{ label: "Save Image", onClick: () => onSave?.() || downloadImage(imageUrl) },
{ label: "Copy Image", onClick: () => onCopy?.() || copyImageToClipboard(imageUrl) },
{ divider: true },
{ label: "Open in New Tab", onClick: () => window.open(imageUrl, "_blank") },
{ label: "Copy URL", onClick: () => copyToClipboard(imageUrl) },
],
forInput: (onCut?: () => void, onCopy?: () => void, onPaste?: () => void, onDelete?: () => void): ContextMenuItem[] => [
{ label: "Cut", onClick: onCut, shortcut: "Ctrl+X", disabled: !onCut },
{ label: "Copy", onClick: onCopy, shortcut: "Ctrl+C", disabled: !onCopy },
{ label: "Paste", onClick: onPaste, shortcut: "Ctrl+V", disabled: !onPaste },
{ divider: true },
{ label: "Delete", onClick: onDelete, danger: true, disabled: !onDelete },
],
forMessage: (onReply?: () => void, onForward?: () => void, onCopy?: () => void, onPin?: () => void, onDelete?: () => void): ContextMenuItem[] => [
{ label: "Reply", onClick: onReply },
{ label: "Forward", onClick: onForward },
{ label: "Copy", onClick: onCopy },
{ divider: true },
{ label: "Pin", onClick: onPin },
{ divider: true },
{ label: "Delete", onClick: onDelete, danger: true },
],
};
// Helper hook for element-level context menu (no circular import)
export function useElementContextMenu<T extends HTMLElement = HTMLDivElement>() {
const ref = useRef<T>(null);
const [contextMenu, setContextMenu] = useState<ContextMenuState>({
visible: false,
position: { x: 0, y: 0 },
items: [],
data: null,
});
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
const showContextMenu = useCallback((
e: React.MouseEvent | MouseEvent,
items: ContextMenuItem[],
data?: any
) => {
e.preventDefault();
e.stopPropagation();
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
setContextMenu({
visible: true,
position: { x: e.clientX, y: e.clientY },
items,
data,
});
}, []);
const hideContextMenu = useCallback(() => {
timeoutRef.current = setTimeout(() => {
setContextMenu(prev => ({ ...prev, visible: false, data: null }));
timeoutRef.current = null;
}, 50);
}, []);
const attach = useCallback((
items: ContextMenuItem[] | ((data?: any) => ContextMenuItem[]),
getData?: () => any
) => {
const element = ref.current;
if (!element) return;
const handler = (e: MouseEvent) => {
e.preventDefault();
const menuItems = typeof items === "function" ? items(getData?.()) : items;
showContextMenu(e, menuItems, getData?.());
};
element.addEventListener("contextmenu", handler);
return () => element.removeEventListener("contextmenu", handler);
}, [showContextMenu]);
// Handle click outside
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
const target = e.target as HTMLElement;
if (contextMenu.visible && !target.closest(".context-menu")) {
hideContextMenu();
}
};
const handleEscape = (e: KeyboardEvent) => {
if (e.key === "Escape" && contextMenu.visible) {
hideContextMenu();
}
};
document.addEventListener("mousedown", handleClickOutside);
document.addEventListener("keydown", handleEscape);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
document.removeEventListener("keydown", handleEscape);
};
}, [contextMenu.visible, hideContextMenu]);
// Cleanup
useEffect(() => {
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, []);
return {
ref,
attach,
contextMenu,
hideContextMenu,
showContextMenu,
};
}

Xet Storage Details

Size:
11.5 kB
·
Xet hash:
954f8ec74e6cc81cbc5b7e487ba83bdd02cc7a9150dff79d1c58602108d47658

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