Spaces:
Running
Running
Commit ·
d63f763
1
Parent(s): ae39bbb
fix
Browse filesFiles changed (2)
774 unmodified lines77577677777877978078113 unmodified lines795796797798799800871 unmodified lines167216731674167516761677774 unmodified lines}}, [projectId]);// --- Save Project Data ---const saveCanvas = useCallback(async (isManual = false) => {13 unmodified linesid: projectId,userId: user.id,title: projectData?.title || 'My Project',nodes: nodes.map(n => ({id: n.id,label: n.data.label,871 unmodified linesredo,canUndo: pastRef.current.length > 0,canRedo: futureRef.current.length > 0,takeHistorySnapshot};};774 unmodified lines77577677777877978078178278378478578678778878979079113 unmodified lines805806807808809810811871 unmodified lines1683168416851686168716881689774 unmodified lines}}, [projectId]);const updateProjectMetadata = useCallback((title, description) => {setProjectData((prev) => {if (!prev) return null;return {...prev,title: title !== undefined ? title : prev.title,description: description !== undefined ? description : prev.description};});setSaveStatus('unsaved');}, []);// --- Save Project Data ---const saveCanvas = useCallback(async (isManual = false) => {13 unmodified linesid: projectId,userId: user.id,title: projectData?.title || 'My Project',description: projectData?.description || '',nodes: nodes.map(n => ({id: n.id,label: n.data.label,871 unmodified linesredo,canUndo: pastRef.current.length > 0,canRedo: futureRef.current.length > 0,takeHistorySnapshot,updateProjectMetadata};};
24 unmodified lines25262728293031323334353637383940753 unmodified lines794795796797798799248 unmodified lines104810491050105110521053105438 unmodified lines109310941095109610971098109973 unmodified lines117311741175117611771178160 unmodified lines13391340134113421343134413451346134713481349135013511352135313541355135613571358135929 unmodified lines1389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014217 unmodified lines14291430143114321433143414358 unmodified lines144414451446144714481449145014511452145314541455145614571458145964 unmodified lines152415251526152715281529153016 unmodified lines15471548154915501551155215531554155554 unmodified lines16101611161216131614161572 unmodified lines168816891690169116921693169424 unmodified lineslet maxX = -Infinity;let maxY = -Infinity;nodes.forEach((node) => {const x = node.position.x;const y = node.position.y;// Guess width and height based on node typeconst w = node.width || (node.type === 'condition' ? 120 : 250);const h = node.height || (node.type === 'condition' ? 120 : 100);if (x < minX) minX = x;if (y < minY) minY = y;if (x + w > maxX) maxX = x + w;if (y + h > maxY) maxY = y + h;});return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };};753 unmodified lines);};// Initials extractor helper for collaborator cursor badgesconst getInitials = (name) => {if (!name) return '';248 unmodified linesconst navigate = useNavigate();const { user } = useAuth();const { isDarkMode } = useTheme();const { screenToFlowPosition } = useReactFlow();const mousePosRef = useRef({ x: window.innerWidth / 2, y: window.innerHeight / 2 });const {38 unmodified linesredo,canUndo,canRedo,takeHistorySnapshot} = useCanvasLogic(id, user);const lastCursorSendRef = useRef(0);73 unmodified linesconst [editingHabitNodeId, setEditingHabitNodeId] = useState(null);const [editingSketchNodeId, setEditingSketchNodeId] = useState(null);const [isShareModalOpen, setIsShareModalOpen] = useState(false);useEffect(() => {const handleConfigureCondition = (e) => {160 unmodified linesevent.preventDefault();event.stopPropagation();const selectedNodes = nodes.filter((n) => n.selected);const selectedEdges = edges.filter((e) => e.selected);if (selectedNodes.length > 0) {selectedNodes.forEach((node) => deleteNode(node.id));}if (selectedEdges.length > 0) {selectedEdges.forEach((edge) => deleteEdge(edge.id));}}};window.addEventListener('keydown', handleKeyDown, { capture: true });return () => window.removeEventListener('keydown', handleKeyDown, { capture: true });}, [nodes, edges, deleteNode, deleteEdge, permission, handleCopy, handleCut, handlePaste, undo, redo]);const handleNodeContextMenu = useCallback((event, node) => {29 unmodified lines);const exportToPng = useCallback(() => {if (!nodes || nodes.length === 0) {alert(t('canvas.export_empty_error'));return;}const nodesBounds = getRectOfNodesCustom(nodes);const imageWidth = 1200;const imageHeight = 800;const transform = getTransformForBoundsCustom(nodesBounds,imageWidth,imageHeight,0.5,2);const element = document.querySelector('.react-flow__viewport');if (!element) return;toPng(element, {backgroundColor: '#ffffff',width: imageWidth,height: imageHeight,style: {width: `${imageWidth}px`,height: `${imageHeight}px`,transform: `translate(${transform[0]}px, ${transform[1]}px) scale(${transform[2]})`,},}).then((dataUrl) => {const a = document.createElement('a');7 unmodified lines}).catch((err) => {console.error(t('canvas.export_error'), err);});}, [nodes, projectTitle, t]);return (<div className="flex h-screen bg-background overflow-hidden" onMouseUp={handleMouseUp}>8 unmodified lines><ChevronLeft size={28} /></button><div><div className="flex items-center gap-3"><h2 className="text-3xl font-display-lg text-primary">{projectTitle || 'Untitled Sketch'}</h2>{isShared && (<span className="px-2.5 py-1 text-[10px] font-extrabold uppercase bg-secondary/15 text-secondary border-2 border-secondary rounded-xl tracking-wider shadow-[2px_2px_0px_0px_var(--color-secondary)]">{permission === 'Edit' ? 'Спільна (Редагування)' : 'Спільна (Читання)'}</span>)}</div><p className="text-xs font-bold uppercase tracking-widest text-on-surface-variant">{t('canvas.strategic_goal_map')}</p></div></div>64 unmodified lineshandlePaste={() => handlePaste(mousePosRef.current)}exportToPng={exportToPng}onDeleteSelected={() => {nodes.filter(n => n.selected).forEach(n => deleteNode(n.id));}}hasSelectedNodes={nodes.some(n => n.selected)}hasClipboardContent={hasClipboardContent}16 unmodified linesonNodesChange={onNodesChange}onEdgesChange={onEdgesChange}onConnect={permission === 'Read' ? undefined : onConnect}onEdgesDelete={permission === 'Read' ? undefined : onEdgesDelete}onEdgeClick={permission === 'Read' ? undefined : (_, edge) => deleteEdge(edge.id)}onNodesDelete={permission === 'Read' ? undefined : (nds) => nds.forEach(n => deleteNode(n.id))}onNodeDragStart={permission === 'Read' ? undefined : () => takeHistorySnapshot()}onNodeContextMenu={handleNodeContextMenu}onPaneClick={() => setContextMenu(null)}54 unmodified lines/>)}{isShareModalOpen && (<ShareModalprojectId={id}72 unmodified lines<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"24 unmodified lines252627282930313233343536373839404142434445464748495051525354555657585960616263646566753 unmodified lines820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944248 unmodified lines119311941195119611971198119938 unmodified lines1238123912401241124212431244124573 unmodified lines13191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356160 unmodified lines15171518151915201521152215231524152515261527152815291530153115321533153429 unmodified lines1564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515967 unmodified lines16041605160616071608160916108 unmodified lines1619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165064 unmodified lines17151716171717181719172017211722172316 unmodified lines17401741174217431744174517461747174854 unmodified lines1803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182872 unmodified lines190119021903190419051906190724 unmodified lineslet maxX = -Infinity;let maxY = -Infinity;nodes.forEach((node) => {const x = typeof node.position?.x === 'number' ? node.position.x : 0;const y = typeof node.position?.y === 'number' ? node.position.y : 0;// Parse dimensions with pixel stripping and fallback defaultsconst parseDimension = (val, typeDefault) => {if (val === undefined || val === null) return typeDefault;if (typeof val === 'number') return isNaN(val) ? typeDefault : val;const parsed = parseInt(String(val).replace(/px/g, ''), 10);return isNaN(parsed) ? typeDefault : parsed;};// Fallbacks based on node typelet defaultW = 260;let defaultH = 180;if (node.type === 'condition') {defaultW = 150;defaultH = 150;} else if (node.type === 'comment') {defaultW = 200;defaultH = 150;}const w = parseDimension(node.measured?.width || node.width || node.style?.width, defaultW);const h = parseDimension(node.measured?.height || node.height || node.style?.height, defaultH);if (x < minX) minX = x;if (y < minY) minY = y;if (x + w > maxX) maxX = x + w;if (y + h > maxY) maxY = y + h;});if (minX === Infinity) minX = 0;if (minY === Infinity) minY = 0;if (maxX === -Infinity) maxX = 800;if (maxY === -Infinity) maxY = 600;return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };};753 unmodified lines);};// Beautiful digital sketchbook styled Project Settings Modalconst ProjectMetadataModal = ({ title, description, onClose, onSave }) => {const { t } = useTranslation();const [editTitle, setEditTitle] = useState(title || '');const [editDesc, setEditDesc] = useState(description || '');const handleSave = () => {onSave(editTitle, editDesc);};return (<div className="fixed inset-0 bg-primary/40 backdrop-blur-md z-[60] flex items-center justify-center p-4">{/* Premium Digital Sketchbook Card Container */}<div className="bg-surface-container-lowest border-4 border-primary rounded-3xl p-8 max-w-md w-full shadow-[8px_8px_0px_0px_var(--color-primary)] relative transition-all">{/* Close Button */}<buttononClick={onClose}className="absolute top-6 right-6 p-1.5 bg-surface-container-lowest hover:bg-red-500/20 border-2 border-primary rounded-xl transition-all cursor-pointer shadow-[2px_2px_0px_0px_var(--color-primary)] hover:scale-105 text-primary"><X size={18} className="text-primary" /></button><h3 className="text-2xl font-display-lg text-primary mb-6 flex items-center gap-2"><Settings size={24} className="text-primary animate-pulse" /><span>Налаштування проекту</span></h3><div className="space-y-5">{/* Title Input */}<div><label className="block text-[11px] font-bold uppercase tracking-widest text-primary/60 mb-2">Назва проекту</label><inputtype="text"value={editTitle}onChange={(e) => setEditTitle(e.target.value)}placeholder="Введіть назву проекту..."className="w-full px-4 py-3 bg-secondary/10 border-2 border-primary rounded-xl font-bold text-primary focus:outline-none focus:bg-surface-container-lowest transition-all shadow-[2px_2px_0px_0px_rgba(49,54,63,0.1)]"/></div>{/* Description Textarea */}<div><label className="block text-[11px] font-bold uppercase tracking-widest text-primary/60 mb-2">Опис проекту</label><textareavalue={editDesc}onChange={(e) => setEditDesc(e.target.value)}placeholder="Додайте опис проекту..."className="w-full h-28 px-4 py-2.5 bg-secondary/10 border-2 border-primary rounded-xl font-bold text-primary focus:outline-none focus:bg-surface-container-lowest transition-all resize-none shadow-[2px_2px_0px_0px_rgba(49,54,63,0.1)] text-xs"/></div>{/* Actions */}<div className="flex items-center gap-4 pt-2"><buttononClick={onClose}className="flex-1 py-3 text-xs font-bold uppercase tracking-wider text-primary border-2 border-primary rounded-xl bg-surface-container-lowest hover:bg-surface-variant transition-all cursor-pointer shadow-[3px_3px_0px_0px_var(--color-primary)] active:translate-y-0.5 active:shadow-[1px_1px_0px_0px_var(--color-primary)]">Скасувати</button><buttononClick={handleSave}className="flex-1 py-3 text-xs font-bold uppercase tracking-wider text-white bg-primary hover:bg-primary/95 border-2 border-primary rounded-xl transition-all cursor-pointer shadow-[3px_3px_0px_0px_var(--color-primary)] active:translate-y-0.5 active:shadow-[1px_1px_0px_0px_var(--color-primary)]">Зберегти</button></div></div></div></div>);};// Premium hand-drawn styled Deletion Confirmation Modalconst DeletionConfirmModal = ({ description, onClose, onConfirm }) => {const { t } = useTranslation();return (<div className="fixed inset-0 bg-primary/45 backdrop-blur-md z-[70] flex items-center justify-center p-4">{/* Hand-drawn style sketchbook dialog */}<div className="bg-surface-container-lowest border-4 border-primary rounded-3xl p-8 max-w-sm w-full shadow-[8px_8px_0px_0px_var(--color-primary)] relative transform hover:scale-[1.01] transition-all duration-200">{/* Warning Icon Container */}<div className="mx-auto w-16 h-16 bg-red-500/10 border-2 border-primary rounded-full flex items-center justify-center mb-6 shadow-[3px_3px_0px_0px_var(--color-primary)]"><Trash2 size={32} className="text-red-500 animate-bounce" /></div><h3 className="text-2xl font-display-lg text-primary text-center mb-3">Підтвердження видалення</h3><p className="text-sm font-semibold text-center text-on-surface-variant mb-8 px-2 leading-relaxed">{description}<span className="block mt-2 text-[11px] font-bold text-red-500/75 uppercase tracking-wider">Цю дію не можна буде скасувати</span></p><div className="flex items-center gap-4"><buttononClick={onClose}className="flex-1 py-3 text-xs font-extrabold uppercase tracking-wider text-primary border-2 border-primary rounded-xl bg-surface-container-lowest hover:bg-surface-variant transition-all cursor-pointer shadow-[3px_3px_0px_0px_var(--color-primary)] active:translate-y-0.5 active:shadow-[1px_1px_0px_0px_var(--color-primary)]">Скасувати</button><buttononClick={onConfirm}className="flex-1 py-3 text-xs font-extrabold uppercase tracking-wider text-white bg-red-500 hover:bg-red-600 border-2 border-primary rounded-xl transition-all cursor-pointer shadow-[3px_3px_0px_0px_var(--color-primary)] active:translate-y-0.5 active:shadow-[1px_1px_0px_0px_var(--color-primary)]">Видалити</button></div></div></div>);};// Initials extractor helper for collaborator cursor badgesconst getInitials = (name) => {if (!name) return '';248 unmodified linesconst navigate = useNavigate();const { user } = useAuth();const { isDarkMode } = useTheme();const { screenToFlowPosition, getNodes } = useReactFlow();const mousePosRef = useRef({ x: window.innerWidth / 2, y: window.innerHeight / 2 });const {38 unmodified linesredo,canUndo,canRedo,takeHistorySnapshot,updateProjectMetadata} = useCanvasLogic(id, user);const lastCursorSendRef = useRef(0);73 unmodified linesconst [editingHabitNodeId, setEditingHabitNodeId] = useState(null);const [editingSketchNodeId, setEditingSketchNodeId] = useState(null);const [isShareModalOpen, setIsShareModalOpen] = useState(false);const [isEditingMetadata, setIsEditingMetadata] = useState(false);const [pendingDeletion, setPendingDeletion] = useState(null); // { nodeIds: [], edgeIds: [], description: "" }const requestDeletion = useCallback((nodeIds = [], edgeIds = []) => {if (permission === 'Read') return;if (nodeIds.length === 0 && edgeIds.length === 0) return;let desc = '';if (nodeIds.length > 0 && edgeIds.length > 0) {desc = `Ви впевнені, що хочете видалити ${nodeIds.length} обраних елементів та зв'язків?`;} else if (nodeIds.length > 1) {desc = `Ви впевнені, що хочете видалити ці ${nodeIds.length} елементів?`;} else if (nodeIds.length === 1) {const nodeObj = nodes.find(n => n.id === nodeIds[0]);const nodeLabel = nodeObj?.data?.label || 'елемент';desc = `Ви впевнені, що хочете видалити елемент "${nodeLabel}"?`;} else if (edgeIds.length > 1) {desc = `Ви впевнені, що хочете видалити ці ${edgeIds.length} зв'язків?`;} else if (edgeIds.length === 1) {desc = `Ви впевнені, що хочете видалити цей зв'язок?`;}setPendingDeletion({ nodeIds, edgeIds, description: desc });}, [nodes, permission]);const handleConfirmDeletion = useCallback(() => {if (!pendingDeletion) return;takeHistorySnapshot();pendingDeletion.nodeIds.forEach(id => deleteNode(id));pendingDeletion.edgeIds.forEach(id => deleteEdge(id));setPendingDeletion(null);}, [pendingDeletion, deleteNode, deleteEdge, takeHistorySnapshot]);useEffect(() => {const handleConfigureCondition = (e) => {160 unmodified linesevent.preventDefault();event.stopPropagation();const selectedNodeIds = nodes.filter((n) => n.selected).map((n) => n.id);const selectedEdgeIds = edges.filter((e) => e.selected).map((e) => e.id);if (selectedNodeIds.length > 0 || selectedEdgeIds.length > 0) {requestDeletion(selectedNodeIds, selectedEdgeIds);}}};window.addEventListener('keydown', handleKeyDown, { capture: true });return () => window.removeEventListener('keydown', handleKeyDown, { capture: true });}, [nodes, edges, deleteNode, deleteEdge, permission, handleCopy, handleCut, handlePaste, undo, redo, requestDeletion]);const handleNodeContextMenu = useCallback((event, node) => {29 unmodified lines);const exportToPng = useCallback(() => {const currentNodes = getNodes();if (!currentNodes || currentNodes.length === 0) {alert(t('canvas.export_empty_error'));return;}const nodesBounds = getRectOfNodesCustom(currentNodes);const padding = 150;// Dynamic width and height to capture 100% of nodes at 1:1 crisp resolutionconst imageWidth = nodesBounds.width + padding * 2;const imageHeight = nodesBounds.height + padding * 2;const element = document.querySelector('.react-flow__viewport');if (!element) return;// Soft sketch styles or matching canvas dark/light modesconst themeBgColor = isDarkMode ? '#141516' : '#fdf8f8';toPng(element, {backgroundColor: themeBgColor,width: imageWidth,height: imageHeight,style: {width: `${imageWidth}px`,height: `${imageHeight}px`,transform: `translate(${-nodesBounds.x + padding}px, ${-nodesBounds.y + padding}px) scale(1)`,},}).then((dataUrl) => {const a = document.createElement('a');7 unmodified lines}).catch((err) => {console.error(t('canvas.export_error'), err);});}, [getNodes, projectTitle, isDarkMode, t]);return (<div className="flex h-screen bg-background overflow-hidden" onMouseUp={handleMouseUp}>8 unmodified lines><ChevronLeft size={28} /></button><divonClick={() => { if (permission !== 'Read') setIsEditingMetadata(true); }}className={`flex flex-col px-3 py-1 rounded-2xl transition-all duration-200 group border border-transparent select-none ${permission !== 'Read' ? 'cursor-pointer hover:bg-secondary/5 hover:border-primary/10' : ''}`}title={permission !== 'Read' ? 'Натисніть, щоб змінити назву чи опис проекту' : ''}><div className="flex items-center gap-3"><h2 className="text-3xl font-display-lg text-primary group-hover:text-primary/85 transition-colors">{projectTitle || 'Untitled Sketch'}</h2>{permission !== 'Read' && (<span className="opacity-0 group-hover:opacity-100 transition-opacity text-primary/40 text-xs font-bold flex items-center gap-1"><Settings size={14} /><span>Редагувати</span></span>)}{isShared && (<span className="px-2.5 py-1 text-[10px] font-extrabold uppercase bg-secondary/15 text-secondary border-2 border-secondary rounded-xl tracking-wider shadow-[2px_2px_0px_0px_var(--color-secondary)]">{permission === 'Edit' ? 'Спільна (Редагування)' : 'Спільна (Читання)'}</span>)}</div><p className="text-xs font-bold uppercase tracking-widest text-on-surface-variant/80 group-hover:text-on-surface-variant truncate max-w-[400px] leading-tight">{projectData?.description || t('canvas.strategic_goal_map')}</p></div></div>64 unmodified lineshandlePaste={() => handlePaste(mousePosRef.current)}exportToPng={exportToPng}onDeleteSelected={() => {const selectedNodeIds = nodes.filter(n => n.selected).map(n => n.id);const selectedEdgeIds = edges.filter(e => e.selected).map(e => e.id);requestDeletion(selectedNodeIds, selectedEdgeIds);}}hasSelectedNodes={nodes.some(n => n.selected)}hasClipboardContent={hasClipboardContent}16 unmodified linesonNodesChange={onNodesChange}onEdgesChange={onEdgesChange}onConnect={permission === 'Read' ? undefined : onConnect}onEdgesDelete={permission === 'Read' ? undefined : (eds) => requestDeletion([], eds.map(e => e.id))}onEdgeClick={permission === 'Read' ? undefined : (_, edge) => requestDeletion([], [edge.id])}onNodesDelete={permission === 'Read' ? undefined : (nds) => requestDeletion(nds.map(n => n.id), [])}onNodeDragStart={permission === 'Read' ? undefined : () => takeHistorySnapshot()}onNodeContextMenu={handleNodeContextMenu}onPaneClick={() => setContextMenu(null)}54 unmodified lines/>)}{isEditingMetadata && (<ProjectMetadataModaltitle={projectTitle}description={projectData?.description || ''}onClose={() => setIsEditingMetadata(false)}onSave={(newTitle, newDesc) => {updateProjectMetadata(newTitle, newDesc);setIsEditingMetadata(false);}}/>)}{pendingDeletion && (<DeletionConfirmModaldescription={pendingDeletion.description}onClose={() => setPendingDeletion(null)}onConfirm={handleConfirmDeletion}/>)}{isShareModalOpen && (<ShareModalprojectId={id}72 unmodified lines<buttononClick={(e) => {e.stopPropagation();requestDeletion([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"
src/features/canvas/hooks/useCanvasLogic.js+14-2
src/pages/CanvasPage.jsx+250-37