Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions src/App.css
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
width: 100%;
margin: 0;
padding: 0;
}

.logo {
Expand Down
238 changes: 161 additions & 77 deletions src/App.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// 📦 Imports
import React, { useState, useRef } from 'react';
import React, { useState, useRef, useCallback, useEffect } from 'react';
import ReactFlow, {
Background,
Controls,
Expand All @@ -15,7 +15,6 @@ import { saveAs } from 'file-saver';
// 🧠 Initial State & Helpers
const initialNodes = [];
const initialEdges = [];
let nodeId = 1;

const getColor = (type) => {
switch (type) {
Expand All @@ -26,18 +25,51 @@ const getColor = (type) => {
}
};

// 🤖 AI Logic with Domino Effect Thinking (Updated: Using Puter AI API)
const createAIChildren = async (text, parentId, setNodes, setEdges, stopGenerationRef) => {
try {
if (stopGenerationRef.current) return;
const res = await axios.post(
'https://api.puter.com/v1/chat/completions',
{
model: 'gpt-3.5-turbo',
messages: [
{
role: 'system',
content: `You are an expert in cause-and-effect analysis.
// 🔧 App Component
export default function App() {
const [nodes, setNodes] = useState(() => {
const saved = localStorage.getItem('nodeverse-nodes');
return saved ? JSON.parse(saved) : initialNodes;
});
const [edges, setEdges] = useState(() => {
const saved = localStorage.getItem('nodeverse-edges');
return saved ? JSON.parse(saved) : initialEdges;
});
const [prompt, setPrompt] = useState('');
const [loading, setLoading] = useState(false);
const stopGenerationRef = useRef(false);
const reactFlowWrapper = useRef(null);
const nodeIdRef = useRef(1);

// 💾 Persist to LocalStorage
useEffect(() => {
localStorage.setItem('nodeverse-nodes', JSON.stringify(nodes));
localStorage.setItem('nodeverse-edges', JSON.stringify(edges));
}, [nodes, edges]);

// 🆔 Initialize Node ID
useEffect(() => {
if (nodes.length > 0) {
const maxId = Math.max(...nodes.map((n) => {
const idNum = parseInt(n.id);
return isNaN(idNum) ? 0 : idNum;
}));
nodeIdRef.current = maxId + 1;
}
}, []);

// 🤖 AI Logic with Domino Effect Thinking (Updated: Using Puter AI API)
const createAIChildren = useCallback(async (text, parentId, parentPos, depth = 1) => {
try {
if (stopGenerationRef.current || depth < 0) return;
const res = await axios.post(
'https://api.puter.com/v1/chat/completions',
{
model: 'gpt-3.5-turbo',
messages: [
{
role: 'system',
content: `You are an expert in cause-and-effect analysis.

Given a news headline or event, break it down into a chain of consequences, like a domino effect.

Expand All @@ -48,73 +80,63 @@ Each node must:
- Be logically linked to the prompt

Return only 3 outputs: one of each type.`
},
{ role: 'user', content: text }
]
},
{
headers: {
'Content-Type': 'application/json'
}
}
);

const content = res.data.choices?.[0]?.message?.content || '';
const lines = content.split('\n').filter(Boolean).slice(0, 3);
const childTypes = ['positive', 'neutral', 'negative'];

const newNodes = lines.map((line, idx) => {
const newId = `${nodeId++}`;
return {
id: newId,
data: { label: line.replace(/^\d+\.\s*/, '') },
position: {
x: 300 + Math.random() * 300,
y: 200 + Math.random() * 300
},
{ role: 'user', content: text }
]
},
style: {
background: getColor(childTypes[idx]),
color: '#fff',
borderRadius: 12,
padding: 10,
fontWeight: 'bold',
fontSize: 14,
maxWidth: 300
{
headers: {
'Content-Type': 'application/json'
}
}
};
});
);

const newEdges = newNodes.map((n) => ({
id: `${parentId}-${n.id}`,
source: parentId,
target: n.id
}));
const content = res.data.choices?.[0]?.message?.content || '';
const lines = content.split('\n').filter(Boolean).slice(0, 3);
const childTypes = ['positive', 'neutral', 'negative'];

setNodes((nds) => [...nds, ...newNodes]);
setEdges((eds) => [...eds, ...newEdges]);
const newNodes = lines.map((line, idx) => {
const newId = `${nodeIdRef.current++}`;
return {
id: newId,
data: { label: line.replace(/^\d+\.\s*/, '') },
position: {
x: parentPos.x + 350,
y: parentPos.y + (idx - 1) * 150
},
style: {
background: getColor(childTypes[idx]),
color: '#fff',
borderRadius: 12,
padding: 10,
fontWeight: 'bold',
fontSize: 14,
maxWidth: 300
}
};
});

// Recursively expand each child one level deep
for (const n of newNodes) {
if (stopGenerationRef.current) break;
await createAIChildren(n.data.label, n.id, setNodes, setEdges, stopGenerationRef);
}
const newEdges = newNodes.map((n) => ({
id: `${parentId}-${n.id}`,
source: parentId,
target: n.id
}));

} catch (err) {
const errMsg = err.response?.data?.error?.message || err.message;
alert(`❌ AI Error: ${errMsg}`);
console.error('❌ Full error:', err.response?.data || err);
}
};
setNodes((nds) => [...nds, ...newNodes]);
setEdges((eds) => [...eds, ...newEdges]);

// Recursively expand each child
for (const n of newNodes) {
if (stopGenerationRef.current) break;
await createAIChildren(n.data.label, n.id, n.position, depth - 1);
}

// 🔧 App Component
export default function App() {
const [nodes, setNodes] = useState(initialNodes);
const [edges, setEdges] = useState(initialEdges);
const [prompt, setPrompt] = useState('');
const [loading, setLoading] = useState(false);
const stopGenerationRef = useRef(false);
const reactFlowWrapper = useRef(null);
} catch (err) {
const errMsg = err.response?.data?.error?.message || err.message;
alert(`❌ AI Error: ${errMsg}`);
console.error('❌ Full error:', err.response?.data || err);
}
}, [setNodes, setEdges]);

const handleExport = () => {
if (reactFlowWrapper.current) {
Expand All @@ -126,12 +148,22 @@ export default function App() {
}
};

const handleClear = () => {
if (window.confirm('Are you sure you want to clear the entire mind map?')) {
setNodes([]);
setEdges([]);
localStorage.removeItem('nodeverse-nodes');
localStorage.removeItem('nodeverse-edges');
nodeIdRef.current = 1;
}
};

const handleSubmit = async () => {
if (!prompt.trim()) return;
setLoading(true);
stopGenerationRef.current = false;

const rootId = `${nodeId++}`;
const rootId = `${nodeIdRef.current++}`;
const rootNode = {
id: rootId,
data: { label: prompt },
Expand All @@ -150,7 +182,7 @@ export default function App() {
setNodes([rootNode]);
setEdges([]);

await createAIChildren(prompt, rootId, setNodes, setEdges, stopGenerationRef);
await createAIChildren(prompt, rootId, rootNode.position);

setPrompt('');
setLoading(false);
Expand All @@ -164,7 +196,7 @@ export default function App() {
const onNodeClick = async (_event, node) => {
stopGenerationRef.current = false;
setLoading(true);
await createAIChildren(node.data.label, node.id, setNodes, setEdges, stopGenerationRef);
await createAIChildren(node.data.label, node.id, node.position);
setLoading(false);
};

Expand Down Expand Up @@ -230,6 +262,22 @@ export default function App() {
>
⏹ Stop
</button>
<button
onClick={handleClear}
disabled={loading || nodes.length === 0}
style={{
padding: '10px 20px',
backgroundColor: '#f44336',
color: 'white',
border: 'none',
borderRadius: '8px',
fontWeight: 'bold',
cursor: loading || nodes.length === 0 ? 'not-allowed' : 'pointer',
opacity: loading || nodes.length === 0 ? 0.7 : 1,
}}
>
Clear All
</button>
<button
onClick={handleExport}
disabled={loading || nodes.length === 0}
Expand All @@ -250,7 +298,7 @@ export default function App() {
</div>

{/* 🧠 ReactFlow Canvas */}
<div style={{ flexGrow: 1 }} ref={reactFlowWrapper}>
<div style={{ flexGrow: 1, position: 'relative' }} ref={reactFlowWrapper}>
<ReactFlow
nodes={nodes}
edges={edges}
Expand All @@ -264,6 +312,42 @@ export default function App() {
<Controls />
<Background variant="dots" gap={12} size={1} />
</ReactFlow>

{/* 🎨 Color Legend Overlay */}
<div style={{
position: 'absolute',
bottom: '20px',
right: '20px',
backgroundColor: 'rgba(34, 34, 34, 0.9)',
padding: '15px',
borderRadius: '10px',
border: '1px solid #444',
color: '#fff',
zIndex: 10,
pointerEvents: 'none',
display: 'flex',
flexDirection: 'column',
gap: '8px',
fontSize: '0.9rem'
}}>
<div style={{ fontWeight: 'bold', marginBottom: '5px', borderBottom: '1px solid #555', paddingBottom: '5px' }}>Legend</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
<div style={{ width: '15px', height: '15px', backgroundColor: '#6200ea', borderRadius: '3px' }}></div>
<span>Root / Origin</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
<div style={{ width: '15px', height: '15px', backgroundColor: '#00c853', borderRadius: '3px' }}></div>
<span>Positive Effect</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
<div style={{ width: '15px', height: '15px', backgroundColor: '#ffd600', borderRadius: '3px' }}></div>
<span>Neutral Effect</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
<div style={{ width: '15px', height: '15px', backgroundColor: '#d50000', borderRadius: '3px' }}></div>
<span>Negative Effect</span>
</div>
</div>
</div>
</div>
);
Expand Down