Spaces:
Running
Running
Commit ·
786fd46
1
Parent(s): e40dcb3
feat(canvas): implement clipboard copy/cut/paste, redesigned left toolbar and context menus
Browse filesFiles changed (3)
1234567891011121314151617181920212223import React from 'react';import { motion } from 'framer-motion';import { useTranslation } from 'react-i18next';import { Sparkles } from 'lucide-react';const CanvasToolbar = ({ handleAIRequest, isAIActive }) => {const { t } = useTranslation();return (<div className="absolute top-28 left-1/2 -translate-x-1/2 z-20 flex items-center gap-4 bg-surface-container-lowest/80 backdrop-blur-md p-3 rough-border shadow-xl"><motion.buttonwhileHover={{ scale: 1.05 }}whileTap={{ scale: 0.95 }}onClick={handleAIRequest}className={`flex items-center gap-2 px-6 py-2 rounded-xl font-bold transition-all ${isAIActive ? 'bg-secondary text-primary rough-border' : 'bg-primary text-on-primary'}`}><Sparkles size={18} /><span>{isAIActive ? t('canvas.ai_thinking', 'AI Thinking...') : t('canvas.ai_assistant', 'AI Assistant')}</span></motion.button></div>);};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176import React, { useState } from 'react';import { motion, AnimatePresence } from 'framer-motion';import { useTranslation } from 'react-i18next';import {Sparkles,Target,GitFork,Timer,Copy,Scissors,Clipboard,Image,Trash2} from 'lucide-react';const TooltipButton = ({ children, tooltip, onClick, disabled = false, className = "" }) => {const [hovered, setHovered] = useState(false);const [hasClipboard, setHasClipboard] = useState(false);const handleMouseEnter = () => {setHovered(true);if (tooltip === 'Вставити' || tooltip === 'Paste') {setHasClipboard(!!(window.__flowClipboard && window.__flowClipboard.nodes && window.__flowClipboard.nodes.length > 0));}};const isBtnDisabled = disabled || ((tooltip === 'Вставити' || tooltip === 'Paste') && !hasClipboard);return (<div className="relative flex items-center"><motion.buttonwhileHover={{ scale: isBtnDisabled ? 1 : 1.05 }}whileTap={{ scale: isBtnDisabled ? 1 : 0.95 }}onClick={onClick}disabled={isBtnDisabled}onMouseEnter={handleMouseEnter}onMouseLeave={() => setHovered(false)}className={`p-2.5 rounded-xl transition-all relative border-2 border-transparent hover:border-primary hover:bg-surface-variant flex items-center justify-center ${isBtnDisabled? 'opacity-35 cursor-not-allowed text-primary/40': 'cursor-pointer text-primary hover:shadow-[2px_2px_0px_0px_var(--color-primary)]'} ${className}`}>{children}</motion.button><AnimatePresence>{hovered && (<motion.divinitial={{ opacity: 0, x: -10 }}animate={{ opacity: 1, x: 0 }}exit={{ opacity: 0, x: -10 }}transition={{ duration: 0.15 }}className="absolute left-full ml-3 px-3 py-1.5 bg-primary text-on-primary font-bold text-xs rounded-md shadow-lg border border-primary/20 whitespace-nowrap z-50 pointer-events-none">{tooltip}<div className="absolute right-full top-1/2 -translate-y-1/2 border-8 border-transparent border-r-primary"></div></motion.div>)}</AnimatePresence></div>);};const CanvasToolbar = ({handleAIRequest,isAIActive,addNewNodeAt,handleCopy,handleCut,handlePaste,exportToPng,onDeleteSelected,hasSelectedNodes}) => {const { t } = useTranslation();return (<div className="absolute top-28 left-6 z-20 flex flex-col items-center gap-3 bg-surface-container-lowest border-2 border-primary shadow-[4px_4px_0px_0px_var(--color-primary)] p-2.5 rounded-2xl transition-all">{/* AI Assistant Section */}<div className="relative group"><motion.buttonwhileHover={{ scale: isAIActive ? 1 : 1.05 }}whileTap={{ scale: isAIActive ? 1 : 0.95 }}onClick={handleAIRequest}className={`p-3 rounded-xl font-bold transition-all flex items-center justify-center relative border-2 ${isAIActive? 'bg-secondary text-primary border-primary shadow-[2px_2px_0px_0px_var(--color-primary)] animate-pulse': 'bg-primary text-on-primary border-transparent hover:border-primary hover:bg-primary/95 hover:shadow-[2px_2px_0px_0px_var(--color-primary)]'}`}><Sparkles size={18} /></motion.button><div className="absolute left-full ml-3 top-1/2 -translate-y-1/2 px-3 py-1.5 bg-primary text-on-primary font-bold text-xs rounded-md shadow-lg border border-primary/20 whitespace-nowrap z-50 pointer-events-none opacity-0 group-hover:opacity-100 transition-opacity">{isAIActive ? t('canvas.ai_thinking', 'AI Thinking...') : t('canvas.ai_assistant', 'AI Assistant')}<div className="absolute right-full top-1/2 -translate-y-1/2 border-8 border-transparent border-r-primary"></div></div></div><div className="w-full h-[1px] bg-primary/10 my-1"></div>{/* Node Creation Section */}<div className="flex flex-col gap-2"><TooltipButtontooltip={t('canvas.toolbar.add_goal', 'Додати ціль')}onClick={() => addNewNodeAt(undefined, undefined, 'sketch')}><Target size={18} /></TooltipButton><TooltipButtontooltip={t('canvas.toolbar.add_condition', 'Додати умову')}onClick={() => addNewNodeAt(undefined, undefined, 'condition')}><GitFork size={18} /></TooltipButton><TooltipButtontooltip={t('canvas.toolbar.add_habit', 'Додати звичку')}onClick={() => addNewNodeAt(undefined, undefined, 'habit')}><Timer size={18} className="text-secondary" /></TooltipButton></div><div className="w-full h-[1px] bg-primary/10 my-1"></div>{/* Clipboard Actions */}<div className="flex flex-col gap-2"><TooltipButtontooltip={t('canvas.toolbar.copy', 'Копіювати')}onClick={handleCopy}disabled={!hasSelectedNodes}><Copy size={18} /></TooltipButton><TooltipButtontooltip={t('canvas.toolbar.cut', 'Вирізати')}onClick={handleCut}disabled={!hasSelectedNodes}><Scissors size={18} /></TooltipButton><TooltipButtontooltip={t('canvas.toolbar.paste', 'Вставити')}onClick={() => handlePaste()}><Clipboard size={18} /></TooltipButton></div><div className="w-full h-[1px] bg-primary/10 my-1"></div>{/* Export & Cleanup */}<div className="flex flex-col gap-2"><TooltipButtontooltip={t('canvas.toolbar.export_png', 'Експорт в PNG')}onClick={exportToPng}><Image size={18} className="text-green-600" /></TooltipButton><TooltipButtontooltip={t('canvas.toolbar.delete_selected', 'Видалити виділене')}onClick={onDeleteSelected}disabled={!hasSelectedNodes}className="hover:bg-red-500/10 hover:text-red-500 hover:border-red-500/30"><Trash2 size={18} className={hasSelectedNodes ? "text-red-500" : ""} /></TooltipButton></div></div>);};
797 unmodified lines79879980080180280380480536 unmodified lines842843844845846847239 unmodified lines108710881089109010911092797 unmodified lines);const addNewNodeAt = useCallback((x, y, type = 'sketch') => {const id = crypto.randomUUID();const position = screenToFlowPosition({ x, y });const nodeData = {label: '',36 unmodified linesreturn id;}, [setNodes, screenToFlowPosition, updateNodeDataCallback]);const submitAICanvasPrompt = async (promptText) => {if (!promptText || !projectId) return false;setAiLoading(true);239 unmodified linessetShowPaywall,handleAIRequest,addNewNodeAt,handleMouseDown,handleMouseUp,saveCanvas,797 unmodified lines79879980080180280380480580680736 unmodified lines84484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001239 unmodified lines124112421243124412451246124712481249797 unmodified lines);const addNewNodeAt = useCallback((x, y, type = 'sketch') => {const finalX = x !== undefined ? x : window.innerWidth / 2;const finalY = y !== undefined ? y : window.innerHeight / 2;const id = crypto.randomUUID();const position = screenToFlowPosition({ x: finalX, y: finalY });const nodeData = {label: '',36 unmodified linesreturn id;}, [setNodes, screenToFlowPosition, updateNodeDataCallback]);const handleCopy = useCallback(() => {const selectedNodes = nodes.filter((n) => n.selected);const selectedEdges = edges.filter((e) => e.selected);if (selectedNodes.length === 0) return;window.__flowClipboard = {nodes: selectedNodes.map(n => ({...n,originalPosition: { ...n.position }})),edges: selectedEdges};}, [nodes, edges]);const handleCut = useCallback(() => {if (projectData?.permission === 'Read') return;const selectedNodes = nodes.filter((n) => n.selected);const selectedEdges = edges.filter((e) => e.selected);if (selectedNodes.length === 0) return;window.__flowClipboard = {nodes: selectedNodes.map(n => ({...n,originalPosition: { ...n.position }})),edges: selectedEdges};selectedNodes.forEach(node => {setNodes((nds) => nds.filter((n) => n.id !== node.id));if (broadcastMessageRef.current) {broadcastMessageRef.current({type: 'NODE_DELETE',payload: { id: node.id }});}});selectedEdges.forEach(edge => {setEdges((eds) => eds.filter((e) => e.id !== edge.id));if (broadcastMessageRef.current) {broadcastMessageRef.current({type: 'EDGE_DELETE',payload: { id: edge.id }});}});}, [nodes, edges, setNodes, setEdges, projectData]);const handlePaste = useCallback((screenCoords = null) => {if (projectData?.permission === 'Read') return;if (!window.__flowClipboard || !window.__flowClipboard.nodes || window.__flowClipboard.nodes.length === 0) return;const { nodes: copiedNodes, edges: copiedEdges } = window.__flowClipboard;// De-select all current nodes/edgessetNodes(nds => nds.map(n => n.selected ? { ...n, selected: false } : n));setEdges(eds => eds.map(e => e.selected ? { ...e, selected: false } : e));const idMap = {};const newNodes = [];const newEdges = [];let getPosition;if (screenCoords) {const flowMousePos = screenToFlowPosition({ x: screenCoords.x, y: screenCoords.y });let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;copiedNodes.forEach(n => {if (n.position.x < minX) minX = n.position.x;if (n.position.y < minY) minY = n.position.y;if (n.position.x > maxX) maxX = n.position.x;if (n.position.y > maxY) maxY = n.position.y;});const centerX = (minX + maxX) / 2;const centerY = (minY + maxY) / 2;getPosition = (n) => ({x: flowMousePos.x + (n.position.x - centerX),y: flowMousePos.y + (n.position.y - centerY)});} else {const offset = 40;getPosition = (n) => ({x: n.position.x + offset,y: n.position.y + offset});}copiedNodes.forEach(node => {const newId = crypto.randomUUID();idMap[node.id] = newId;const pastedNode = {...node,id: newId,selected: true,position: getPosition(node),data: {...node.data,updateNodeData: updateNodeDataCallback}};delete pastedNode.originalPosition;newNodes.push(pastedNode);});copiedEdges.forEach(edge => {const newSource = idMap[edge.source];const newTarget = idMap[edge.target];if (newSource && newTarget) {const newEdgeId = `edge-${crypto.randomUUID()}`;const pastedEdge = {...edge,id: newEdgeId,source: newSource,target: newTarget,selected: true};newEdges.push(pastedEdge);}});setNodes(nds => nds.concat(newNodes));setEdges(eds => eds.concat(newEdges));if (broadcastMessageRef.current) {newNodes.forEach(n => {broadcastMessageRef.current({type: 'NODE_ADD',payload: n});});newEdges.forEach(e => {broadcastMessageRef.current({type: 'EDGE_ADD',payload: e});});}// Update window.__flowClipboard positions so subsequent pastes cascade shift!window.__flowClipboard.nodes = copiedNodes.map((n, idx) => ({...n,position: newNodes[idx].position}));}, [setNodes, setEdges, screenToFlowPosition, updateNodeDataCallback, projectData]);const submitAICanvasPrompt = async (promptText) => {if (!promptText || !projectId) return false;setAiLoading(true);239 unmodified linessetShowPaywall,handleAIRequest,addNewNodeAt,handleCopy,handleCut,handlePaste,handleMouseDown,handleMouseUp,saveCanvas,
56 unmodified lines57585960616263640 unmodified lines704705706707708709190 unmodified lines9009019029039049059065 unmodified lines91291391491591691711 unmodified lines929930931932933934935157 unmodified lines109310941095109610971098109980 unmodified lines11801181118211831184118511861187118811891190119111921193119411959 unmodified lines12051206120712081209121030 unmodified lines1241124212431244124512461247124812491250125156 unmodified linesimport Sidebar from '../components/Sidebar';import { useAuth } from '../context/AuthContext';import { useTheme } from '../context/ThemeContext';import { Maximize2, Play, Settings, Save, ChevronLeft, Loader2, Trash2, Target, GitFork, Image, X, Plus, Timer, Milestone, Share2, User } from 'lucide-react';// Feature componentsimport SketchNode from '../features/canvas/components/nodes/SketchNode';640 unmodified linessetShowPaywall,handleAIRequest,addNewNodeAt,handleMouseDown,handleMouseUp,saveCanvas,190 unmodified linesreturn () => window.removeEventListener('click', handleCloseMenu);}, []);// Handle global keyboard Delete/Backspace key to delete selected nodes or edgesuseEffect(() => {const handleKeyDown = (event) => {// Ignore key events when typing in inputs/textareas5 unmodified linesreturn;}if (event.key === 'Delete' || event.key === 'Backspace') {if (permission === 'Read') return; // Read-only restriction!11 unmodified lineswindow.addEventListener('keydown', handleKeyDown);return () => window.removeEventListener('keydown', handleKeyDown);}, [nodes, edges, deleteNode, deleteEdge, permission]);const handleNodeContextMenu = useCallback((event, node) => {157 unmodified lines<CanvasToolbarhandleAIRequest={handleAIRequest}isAIActive={isAIActive}user={user}/>)}80 unmodified lines{contextMenu && contextMenu.type === 'node' && (<divstyle={{ top: contextMenu.y, left: contextMenu.x }}className="absolute bg-surface-container-lowest border-2 border-primary shadow-[2px_2px_0px_0px_var(--color-primary)] py-1 px-1 z-50 min-w-[110px] rounded-lg transition-all"onClick={(e) => e.stopPropagation()}><buttononClick={(e) => {e.stopPropagation();deleteNode(contextMenu.nodeId);setContextMenu(null);}}className="w-full text-left px-2 py-1 hover:bg-red-500/20 text-red-600 hover:text-red-700 font-bold rounded-md transition-colors flex items-center justify-center gap-1.5 text-xs"><Trash2 size={14} /><span>{t('canvas.context_menu.delete')}</span>9 unmodified lines>{permission !== 'Read' && (<><div className="px-2.5 py-1 text-[9px] font-bold uppercase tracking-widest text-on-surface-variant/40 border-b border-primary/10">{t('canvas.context_menu.create_node')}</div>30 unmodified lines<Timer size={15} className="text-secondary" /><span>{t('canvas.context_menu.habit_node')}</span></button><div className="border-t border-primary/10 my-0.5"></div></>)}<buttononClick={(e) => {e.stopPropagation();56 unmodified lines57585960616263640 unmodified lines704705706707708709710711712190 unmodified lines9039049059069079089095 unmodified lines91591691791891992092192292392492592692792892993093193293393493593693793893994094111 unmodified lines953954955956957958959157 unmodified lines111711181119112011211122112311241125112611271128112911301131113280 unmodified lines12131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412859 unmodified lines129512961297129812991300130113021303130413051306130713081309131013111312131313141315131630 unmodified lines1347134813491350135113521353135413551356135756 unmodified linesimport Sidebar from '../components/Sidebar';import { useAuth } from '../context/AuthContext';import { useTheme } from '../context/ThemeContext';import { Maximize2, Play, Settings, Save, ChevronLeft, Loader2, Trash2, Target, GitFork, Image, X, Plus, Timer, Milestone, Share2, User, Copy, Scissors, Clipboard } from 'lucide-react';// Feature componentsimport SketchNode from '../features/canvas/components/nodes/SketchNode';640 unmodified linessetShowPaywall,handleAIRequest,addNewNodeAt,handleCopy,handleCut,handlePaste,handleMouseDown,handleMouseUp,saveCanvas,190 unmodified linesreturn () => window.removeEventListener('click', handleCloseMenu);}, []);// Handle global keyboard shortcuts: Copy/Cut/Paste/Delete/BackspaceuseEffect(() => {const handleKeyDown = (event) => {// Ignore key events when typing in inputs/textareas5 unmodified linesreturn;}// Ctrl+C / Cmd+C (Copy)if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'c') {event.preventDefault();handleCopy();return;}// Ctrl+X / Cmd+X (Cut)if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'x') {event.preventDefault();handleCut();return;}// Ctrl+V / Cmd+V (Paste)if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'v') {event.preventDefault();handlePaste();return;}if (event.key === 'Delete' || event.key === 'Backspace') {if (permission === 'Read') return; // Read-only restriction!11 unmodified lineswindow.addEventListener('keydown', handleKeyDown);return () => window.removeEventListener('keydown', handleKeyDown);}, [nodes, edges, deleteNode, deleteEdge, permission, handleCopy, handleCut, handlePaste]);const handleNodeContextMenu = useCallback((event, node) => {157 unmodified lines<CanvasToolbarhandleAIRequest={handleAIRequest}isAIActive={isAIActive}user={user}addNewNodeAt={addNewNodeAt}handleCopy={handleCopy}handleCut={handleCut}handlePaste={handlePaste}exportToPng={exportToPng}onDeleteSelected={() => {nodes.filter(n => n.selected).forEach(n => deleteNode(n.id));}}hasSelectedNodes={nodes.some(n => n.selected)}/>)}80 unmodified lines{contextMenu && contextMenu.type === 'node' && (<divstyle={{ top: contextMenu.y, left: contextMenu.x }}className="absolute bg-surface-container-lowest border-2 border-primary shadow-[2px_2px_0px_0px_var(--color-primary)] py-1.5 px-1 z-50 min-w-[135px] rounded-lg transition-all flex flex-col gap-0.5"onClick={(e) => e.stopPropagation()}><buttononClick={(e) => {e.stopPropagation();// Ensure node is selected for copy if it isn't alreadyconst targetNode = nodes.find(n => n.id === contextMenu.nodeId);if (targetNode) {const isSelected = targetNode.selected;if (!isSelected) {setNodes(nds => nds.map(n => n.id === contextMenu.nodeId ? { ...n, selected: true } : n));}// Copy node(s)const selectedNodes = nodes.filter(n => n.selected || n.id === contextMenu.nodeId);const selectedEdges = edges.filter(edge =>selectedNodes.some(n => n.id === edge.source) &&selectedNodes.some(n => n.id === edge.target));window.__flowClipboard = {nodes: selectedNodes.map(n => ({ ...n, originalPosition: { ...n.position } })),edges: selectedEdges};}setContextMenu(null);}}className="w-full text-left px-2.5 py-1.5 hover:bg-surface-variant text-primary font-bold rounded-md transition-colors flex items-center gap-2 text-xs"><Copy size={14} className="text-primary" /><span>{t('canvas.context_menu.copy', 'Копіювати')}</span></button><buttononClick={(e) => {e.stopPropagation();// Cut node(s)const targetNode = nodes.find(n => n.id === contextMenu.nodeId);if (targetNode) {const selectedNodes = nodes.filter(n => n.selected || n.id === contextMenu.nodeId);const selectedEdges = edges.filter(edge =>selectedNodes.some(n => n.id === edge.source) &&selectedNodes.some(n => n.id === edge.target));window.__flowClipboard = {nodes: selectedNodes.map(n => ({ ...n, originalPosition: { ...n.position } })),edges: selectedEdges};// Delete selected nodesselectedNodes.forEach(n => deleteNode(n.id));}setContextMenu(null);}}className="w-full text-left px-2.5 py-1.5 hover:bg-surface-variant text-primary font-bold rounded-md transition-colors flex items-center gap-2 text-xs"><Scissors size={14} className="text-primary" /><span>{t('canvas.context_menu.cut', 'Вирізати')}</span></button><div className="border-t border-primary/10 my-0.5"></div><buttononClick={(e) => {e.stopPropagation();deleteNode(contextMenu.nodeId);setContextMenu(null);}}className="w-full text-left px-2.5 py-1.5 hover:bg-red-500/20 text-red-600 hover:text-red-700 font-bold rounded-md transition-colors flex items-center gap-2 text-xs"><Trash2 size={14} /><span>{t('canvas.context_menu.delete')}</span>9 unmodified lines>{permission !== 'Read' && (<>{window.__flowClipboard && window.__flowClipboard.nodes && window.__flowClipboard.nodes.length > 0 && (<><buttononClick={(e) => {e.stopPropagation();handlePaste({ x: contextMenu.clientX, y: contextMenu.clientY });setContextMenu(null);}}className="w-full text-left px-2.5 py-1.5 hover:bg-surface-variant text-primary font-bold rounded-md transition-colors flex items-center gap-2 text-xs"><Clipboard size={15} className="text-primary" /><span>{t('canvas.context_menu.paste', 'Вставити')}</span></button><div className="border-t border-primary/10 my-0.5"></div></>)}<div className="px-2.5 py-1 text-[9px] font-bold uppercase tracking-widest text-on-surface-variant/40 border-b border-primary/10">{t('canvas.context_menu.create_node')}</div>30 unmodified lines<Timer size={15} className="text-secondary" /><span>{t('canvas.context_menu.habit_node')}</span></button><div className="border-t border-primary/10 my-0.5"></div></>)}<buttononClick={(e) => {e.stopPropagation();
src/features/canvas/components/CanvasToolbar.jsx+168-15
src/features/canvas/hooks/useCanvasLogic.js+158-1
src/pages/CanvasPage.jsx+114-8