Compare commits
54 Commits
feat/gestu
...
feat/monit
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a0a4687aeb | ||
|
|
6e1eb25bbc | ||
|
|
a1e242e391 | ||
|
|
c9df87929b | ||
|
|
57ebe724db | ||
|
|
794e638081 | ||
|
|
12ef2ef86e | ||
|
|
0fefefe7f0 | ||
|
|
9601f56ea9 | ||
|
|
873b1cfb0b | ||
|
|
4bd67debf3 | ||
|
|
e53e1a3958 | ||
|
|
7a89b0aedd | ||
|
|
7b05c7344c | ||
|
|
d80ced547c | ||
|
|
cd1aa84f89 | ||
|
|
469a6c7a69 | ||
|
|
b0a5e4770c | ||
|
|
f0fe520ea0 | ||
|
|
b10dbae488 | ||
|
|
faaf67138d | ||
|
|
ed2e0ecb7b | ||
|
|
c25073f20d | ||
|
|
905b9da815 | ||
|
|
58ab95eee1 | ||
|
|
62c8118650 | ||
|
|
d5480f957b | ||
|
|
062e9e3f38 | ||
|
|
8149d67491 | ||
|
|
647ea1979a | ||
|
|
501f56e009 | ||
|
|
ed11680771 | ||
|
|
1bfcfc0458 | ||
|
|
95397ceccc | ||
|
|
e9ea0fb37e | ||
|
|
413fb05cd8 | ||
|
|
c167144b4d | ||
|
|
f0c250626f | ||
|
|
d9faeafe32 | ||
|
|
518045ed1c | ||
|
|
fe13017f2d | ||
|
|
3bcc865dd8 | ||
|
|
7640c32830 | ||
|
|
a95fbd15e6 | ||
|
|
d4393e7635 | ||
|
|
2261da9915 | ||
|
|
c5d9b8342d | ||
|
|
381fdaca1a | ||
|
|
5287cb3bf3 | ||
|
|
221fbe42c2 | ||
|
|
22da2ca664 | ||
|
|
bb7d24b7be | ||
|
|
3cbf983b41 | ||
|
|
45e133e255 |
@@ -15,6 +15,7 @@ type Setter<T> = (value: T | ((prev: T) => T)) => void;
|
|||||||
*/
|
*/
|
||||||
const optionMapping = new Map([
|
const optionMapping = new Map([
|
||||||
["ALL", 0],
|
["ALL", 0],
|
||||||
|
["LLM", 9],
|
||||||
["DEBUG", 10],
|
["DEBUG", 10],
|
||||||
["INFO", 20],
|
["INFO", 20],
|
||||||
["WARNING", 30],
|
["WARNING", 30],
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ import {cell, type Cell} from "../../utils/cellStore.ts";
|
|||||||
export type LogRecord = {
|
export type LogRecord = {
|
||||||
name: string;
|
name: string;
|
||||||
message: string;
|
message: string;
|
||||||
levelname: 'DEBUG' | 'INFO' | 'WARNING' | 'ERROR' | 'CRITICAL' | string;
|
levelname: 'LLM' | 'DEBUG' | 'INFO' | 'WARNING' | 'ERROR' | 'CRITICAL' | string;
|
||||||
levelno: number;
|
levelno: number;
|
||||||
created: number;
|
created: number;
|
||||||
relativeCreated: number;
|
relativeCreated: number;
|
||||||
|
|||||||
@@ -8,6 +8,9 @@
|
|||||||
background-color: #242424;
|
background-color: #242424;
|
||||||
|
|
||||||
--accent-color: #008080;
|
--accent-color: #008080;
|
||||||
|
--panel-shadow:
|
||||||
|
0 1px 2px white,
|
||||||
|
0 8px 24px rgba(190, 186, 186, 0.253);
|
||||||
|
|
||||||
font-synthesis: none;
|
font-synthesis: none;
|
||||||
text-rendering: optimizeLegibility;
|
text-rendering: optimizeLegibility;
|
||||||
@@ -15,6 +18,14 @@
|
|||||||
-moz-osx-font-smoothing: grayscale;
|
-moz-osx-font-smoothing: grayscale;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
:root {
|
||||||
|
--panel-shadow:
|
||||||
|
0 1px 2px rgba(221, 221, 221, 0.178),
|
||||||
|
0 8px 24px rgba(27, 27, 27, 0.507);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
html, body, #root {
|
html, body, #root {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
padding: 0;
|
padding: 0;
|
||||||
@@ -26,7 +37,6 @@ html, body, #root {
|
|||||||
}
|
}
|
||||||
|
|
||||||
a {
|
a {
|
||||||
font-weight: 500;
|
|
||||||
color: canvastext;
|
color: canvastext;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
204
src/pages/MonitoringPage/Components.tsx
Normal file
204
src/pages/MonitoringPage/Components.tsx
Normal file
@@ -0,0 +1,204 @@
|
|||||||
|
import React, { useEffect, useState } from 'react';
|
||||||
|
import styles from './MonitoringPage.module.css';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HELPER: Unified sender function
|
||||||
|
* In a real app, you might move this to a /services or /hooks folder
|
||||||
|
*/
|
||||||
|
const sendUserInterrupt = async (type: string, context: string) => {
|
||||||
|
try {
|
||||||
|
const response = await fetch("http://localhost:8000/button_pressed", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ type, context }),
|
||||||
|
});
|
||||||
|
if (!response.ok) throw new Error("Backend response error");
|
||||||
|
console.log(`Interrupt Sent - Type: ${type}, Context: ${context}`);
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`Failed to send interrupt:`, err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- GESTURE COMPONENT ---
|
||||||
|
export const GestureControls: React.FC = () => {
|
||||||
|
const [selectedGesture, setSelectedGesture] = useState("animations/Stand/BodyTalk/Speaking/BodyTalk_1");
|
||||||
|
|
||||||
|
const gestures = [
|
||||||
|
{ label: "Body Talk 1", value: "animations/Stand/BodyTalk/Speaking/BodyTalk_1" },
|
||||||
|
{ label: "Thinking 8", value: "animations/Stand/Gestures/Thinking_8" },
|
||||||
|
{ label: "Thinking 1", value: "animations/Stand/Gestures/Thinking_1" },
|
||||||
|
{ label: "Happy", value: "animations/Stand/Emotions/Positive/Happy_1" },
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={styles.gestures}>
|
||||||
|
<h4>Gestures</h4>
|
||||||
|
<div className={styles.gestureInputGroup}>
|
||||||
|
<select
|
||||||
|
value={selectedGesture}
|
||||||
|
onChange={(e) => setSelectedGesture(e.target.value)}
|
||||||
|
>
|
||||||
|
{gestures.map(g => <option key={g.value} value={g.value}>{g.label}</option>)}
|
||||||
|
</select>
|
||||||
|
<button onClick={() => sendUserInterrupt("gesture", selectedGesture)}>
|
||||||
|
Actuate
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- PRESET SPEECH COMPONENT ---
|
||||||
|
export const SpeechPresets: React.FC = () => {
|
||||||
|
const phrases = [
|
||||||
|
{ label: "Hello, I'm Pepper", text: "Hello, I'm Pepper" },
|
||||||
|
{ label: "Repeat please", text: "Could you repeat that please" },
|
||||||
|
{ label: "About yourself", text: "Tell me something about yourself" },
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={styles.speech}>
|
||||||
|
<h4>Speech Presets</h4>
|
||||||
|
<ul>
|
||||||
|
{phrases.map((phrase, i) => (
|
||||||
|
<li key={i}>
|
||||||
|
<button
|
||||||
|
className={styles.speechBtn}
|
||||||
|
onClick={() => sendUserInterrupt("speech", phrase.text)}
|
||||||
|
>
|
||||||
|
"{phrase.label}"
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- DIRECT SPEECH (INPUT) COMPONENT ---
|
||||||
|
export const DirectSpeechInput: React.FC = () => {
|
||||||
|
const [text, setText] = useState("");
|
||||||
|
|
||||||
|
const handleSend = () => {
|
||||||
|
if (!text.trim()) return;
|
||||||
|
sendUserInterrupt("speech", text);
|
||||||
|
setText(""); // Clear after sending
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={styles.directSpeech}>
|
||||||
|
<h4>Direct Pepper Speech</h4>
|
||||||
|
<div className={styles.speechInput}>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={text}
|
||||||
|
onChange={(e) => setText(e.target.value)}
|
||||||
|
placeholder="Type message..."
|
||||||
|
onKeyDown={(e) => e.key === 'Enter' && handleSend()}
|
||||||
|
/>
|
||||||
|
<button onClick={handleSend}>Send</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- interface for goals/triggers/norms/conditional norms ---
|
||||||
|
type StatusItem = {
|
||||||
|
id?: string | number;
|
||||||
|
achieved?: boolean;
|
||||||
|
description?: string;
|
||||||
|
label?: string;
|
||||||
|
norm?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
interface StatusListProps {
|
||||||
|
title: string;
|
||||||
|
items: StatusItem[];
|
||||||
|
type: 'goal' | 'trigger' | 'norm'| 'cond_norm';
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- STATUS LIST COMPONENT ---
|
||||||
|
export const StatusList: React.FC<StatusListProps> = ({ title, items, type }) => {
|
||||||
|
return (
|
||||||
|
<section className={styles.phaseBox}>
|
||||||
|
<h3>{title}</h3>
|
||||||
|
<ul>
|
||||||
|
{items.length > 0 ? (
|
||||||
|
items.map((item, idx) => {
|
||||||
|
const isAchieved = item.achieved;
|
||||||
|
const showIndicator = type !== 'norm';
|
||||||
|
const canOverride = showIndicator && !isAchieved;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<li key={item.id ?? idx} className={styles.statusItem}>
|
||||||
|
{showIndicator && (
|
||||||
|
<span
|
||||||
|
className={`${styles.statusIndicator} ${canOverride ? styles.clickable : ''}`}
|
||||||
|
onClick={() => canOverride && sendUserInterrupt("override", String(item.id))}
|
||||||
|
title={canOverride ? `Send override for ID: ${item.id}` : 'Achieved'}
|
||||||
|
style={{ cursor: canOverride ? 'pointer' : 'default' }}
|
||||||
|
>
|
||||||
|
{isAchieved ? "✔️" : "❌"}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<span className={styles.itemDescription}>
|
||||||
|
{item.description || item.label || item.norm}
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})
|
||||||
|
) : (
|
||||||
|
<p className={styles.emptyText}>No {title.toLowerCase()} defined.</p>
|
||||||
|
)}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
// --- Robot Connected ---
|
||||||
|
export const RobotConnected = () => {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The current connection state:
|
||||||
|
* - `true`: Robot is connected.
|
||||||
|
* - `false`: Robot is not connected.
|
||||||
|
* - `null`: Connection status is unknown (initial check in progress).
|
||||||
|
*/
|
||||||
|
const [connected, setConnected] = useState<boolean | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// Open a Server-Sent Events (SSE) connection to receive live ping updates.
|
||||||
|
// We're expecting a stream of data like that looks like this: `data = False` or `data = True`
|
||||||
|
const eventSource = new EventSource("http://localhost:8000/robot/ping_stream");
|
||||||
|
eventSource.onmessage = (event) => {
|
||||||
|
|
||||||
|
// Expecting messages in JSON format: `true` or `false`
|
||||||
|
console.log("received message:", event.data);
|
||||||
|
try {
|
||||||
|
const data = JSON.parse(event.data);
|
||||||
|
|
||||||
|
try {
|
||||||
|
setConnected(data)
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
console.log("couldnt extract connected from incoming ping data")
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch {
|
||||||
|
console.log("Ping message not in correct format:", event.data);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Clean up the SSE connection when the component unmounts.
|
||||||
|
return () => eventSource.close();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<h3>Connection:</h3>
|
||||||
|
<p className={connected ? styles.connected : styles.disconnected }>{connected ? "● Robot is connected" : "● Robot is disconnected"}</p>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
220
src/pages/MonitoringPage/MonitoringPage.module.css
Normal file
220
src/pages/MonitoringPage/MonitoringPage.module.css
Normal file
@@ -0,0 +1,220 @@
|
|||||||
|
.dashboardContainer {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 2fr 1fr; /* Left = content, Right = logs */
|
||||||
|
grid-template-rows: auto 1fr auto; /* Header, Main, Footer */
|
||||||
|
grid-template-areas:
|
||||||
|
"header logs"
|
||||||
|
"main logs"
|
||||||
|
"footer footer";
|
||||||
|
gap: 1rem;
|
||||||
|
padding: 1rem;
|
||||||
|
background-color: var(--bg-main);
|
||||||
|
color: var(--text-main);
|
||||||
|
font-family: Arial, sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* HEADER */
|
||||||
|
.experimentOverview {
|
||||||
|
grid-area: header;
|
||||||
|
display: flex;
|
||||||
|
color: color;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: flex-start;
|
||||||
|
background: var(--bg-surface);
|
||||||
|
color: var(--text-main);
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
padding: 1rem;
|
||||||
|
box-shadow: var(--panel-shadow);
|
||||||
|
position: static; /* ensures it scrolls away */
|
||||||
|
}
|
||||||
|
|
||||||
|
.phaseProgress {
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.phase {
|
||||||
|
display: inline-block;
|
||||||
|
width: 25px;
|
||||||
|
height: 25px;
|
||||||
|
margin: 0 3px;
|
||||||
|
text-align: center;
|
||||||
|
line-height: 25px;
|
||||||
|
background: gray;
|
||||||
|
}
|
||||||
|
|
||||||
|
.completed {
|
||||||
|
background-color: green;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.current {
|
||||||
|
background-color: rgb(255, 123, 0);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.connected {
|
||||||
|
color: green;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
.disconnected {
|
||||||
|
color: red;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pausePlayInactive{
|
||||||
|
background-color: gray;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pausePlayActive{
|
||||||
|
background-color: green;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.next {
|
||||||
|
background-color: #6c757d;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.restartPhase{
|
||||||
|
background-color: rgb(255, 123, 0);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.restartExperiment{
|
||||||
|
background-color: red;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* MAIN GRID */
|
||||||
|
.phaseOverview {
|
||||||
|
grid-area: main;
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, 1fr);
|
||||||
|
grid-template-rows: repeat(2, auto);
|
||||||
|
gap: 1rem;
|
||||||
|
background: var(--bg-surface);
|
||||||
|
color: var(--text-main);
|
||||||
|
padding: 1rem;
|
||||||
|
box-shadow: var(--panel-shadow);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
.phaseBox {
|
||||||
|
background: var(--bg-surface);
|
||||||
|
border: 1px solid var(--border-color);
|
||||||
|
box-shadow: var(--panel-shadow);
|
||||||
|
padding: 1rem;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.phaseOverviewText {
|
||||||
|
grid-column: 1 / -1; /* make the title span across both columns */
|
||||||
|
font-size: 1.4rem;
|
||||||
|
font-weight: 600;
|
||||||
|
margin: 0; /* remove default section margin */
|
||||||
|
padding: 0.25rem 0; /* smaller internal space */
|
||||||
|
}
|
||||||
|
|
||||||
|
.phaseOverviewText h3{
|
||||||
|
margin: 0; /* removes top/bottom whitespace */
|
||||||
|
padding: 0; /* keeps spacing tight */
|
||||||
|
}
|
||||||
|
|
||||||
|
.phaseBox h3 {
|
||||||
|
margin-top: 0;
|
||||||
|
border-bottom: 1px solid var(--border-color);
|
||||||
|
padding-bottom: 0.4rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.checked::before {
|
||||||
|
content: '✔️ ';
|
||||||
|
}
|
||||||
|
|
||||||
|
/* LOGS */
|
||||||
|
.logs {
|
||||||
|
grid-area: logs;
|
||||||
|
background: var(--bg-surface);
|
||||||
|
color: var(--text-main);
|
||||||
|
box-shadow: var(--panel-shadow);
|
||||||
|
padding: 1rem;
|
||||||
|
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.logs textarea {
|
||||||
|
width: 100%;
|
||||||
|
height: 83%;
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
background-color: Canvas;
|
||||||
|
color: CanvasText;
|
||||||
|
border: 1px solid var(--border-color);
|
||||||
|
}
|
||||||
|
|
||||||
|
.logs button {
|
||||||
|
background: var(--bg-surface);
|
||||||
|
box-shadow: var(--panel-shadow);
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
margin-left: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* FOOTER */
|
||||||
|
.controlsSection {
|
||||||
|
grid-area: footer;
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 1rem;
|
||||||
|
background: var(--bg-surface);
|
||||||
|
color: var(--text-main);
|
||||||
|
box-shadow: var(--panel-shadow);
|
||||||
|
padding: 1rem;
|
||||||
|
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.controlsSection button {
|
||||||
|
background: var(--bg-surface);
|
||||||
|
box-shadow: var(--panel-shadow);
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
margin-left: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gestures,
|
||||||
|
.speech,
|
||||||
|
.directSpeech {
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.speechInput {
|
||||||
|
display: flex;
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.speechInput input {
|
||||||
|
flex: 1;
|
||||||
|
padding: 0.5rem;
|
||||||
|
background-color: Canvas;
|
||||||
|
color: CanvasText;
|
||||||
|
border: 1px solid var(--border-color);
|
||||||
|
}
|
||||||
|
|
||||||
|
.speechInput button {
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
padding: 0.5rem 1rem;
|
||||||
|
cursor: pointer;
|
||||||
|
background-color: Canvas;
|
||||||
|
color: CanvasText;
|
||||||
|
border: 1px solid var(--border-color);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* RESPONSIVE */
|
||||||
|
@media (max-width: 900px) {
|
||||||
|
.phaseOverview {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
|
||||||
|
.controlsSection {
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
}
|
||||||
176
src/pages/MonitoringPage/MonitoringPage.tsx
Normal file
176
src/pages/MonitoringPage/MonitoringPage.tsx
Normal file
@@ -0,0 +1,176 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import styles from './MonitoringPage.module.css';
|
||||||
|
import useProgramStore from "../../utils/programStore.ts";
|
||||||
|
import { GestureControls, SpeechPresets, DirectSpeechInput, StatusList, RobotConnected } from './Components';
|
||||||
|
import { nextPhase, pauseExperiment, playExperiment, resetExperiment, resetPhase } from ".//MonitoringPageAPI.ts"
|
||||||
|
|
||||||
|
type Goal = { id?: string | number; description?: string; achieved?: boolean };
|
||||||
|
type Trigger = { id?: string | number; label?: string ; achieved?: boolean };
|
||||||
|
type Norm = { id?: string | number; norm?: string };
|
||||||
|
|
||||||
|
|
||||||
|
const MonitoringPage: React.FC = () => {
|
||||||
|
const getPhaseIds = useProgramStore((s) => s.getPhaseIds);
|
||||||
|
const getNormsInPhase = useProgramStore((s) => s.getNormsInPhase);
|
||||||
|
const getGoalsInPhase = useProgramStore((s) => s.getGoalsInPhase);
|
||||||
|
const getTriggersInPhase = useProgramStore((s) => s.getTriggersInPhase);
|
||||||
|
|
||||||
|
// Can be used to block actions until feedback from CB.
|
||||||
|
const [loading, setLoading] = React.useState(false);
|
||||||
|
const [isPlaying, setIsPlaying] = React.useState(false);
|
||||||
|
|
||||||
|
const phaseIds = getPhaseIds();
|
||||||
|
const [phaseIndex, _] = React.useState(0);
|
||||||
|
|
||||||
|
if (phaseIds.length === 0) {
|
||||||
|
return <p className={styles.empty}>No program loaded.</p>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const phaseId = phaseIds[phaseIndex];
|
||||||
|
|
||||||
|
const goals = getGoalsInPhase(phaseId) as Goal[];
|
||||||
|
const triggers = getTriggersInPhase(phaseId) as Trigger[];
|
||||||
|
const norms = getNormsInPhase(phaseId) as Norm[];
|
||||||
|
|
||||||
|
// Handle logic of 'next' button.
|
||||||
|
|
||||||
|
const handleButton = async (button: string, _context?: string, _endpoint?: string) => {
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
switch (button) {
|
||||||
|
case "pause":
|
||||||
|
await pauseExperiment();
|
||||||
|
break;
|
||||||
|
case "play":
|
||||||
|
await playExperiment();
|
||||||
|
break;
|
||||||
|
case "nextPhase":
|
||||||
|
await nextPhase();
|
||||||
|
break;
|
||||||
|
case "resetPhase":
|
||||||
|
await resetPhase();
|
||||||
|
break;
|
||||||
|
case "resetExperiment":
|
||||||
|
await resetExperiment();
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className={styles.dashboardContainer}>
|
||||||
|
{/* HEADER */}
|
||||||
|
<header className={styles.experimentOverview}>
|
||||||
|
<div className={styles.phaseName}>
|
||||||
|
<h2>Experiment Overview</h2>
|
||||||
|
<p><strong>Phase name:</strong> Rhyming fish</p>
|
||||||
|
<div className={styles.phaseProgress}>
|
||||||
|
<span className={`${styles.phase} ${styles.completed}`}>1</span>
|
||||||
|
<span className={`${styles.phase} ${styles.completed}`}>2</span>
|
||||||
|
<span className={`${styles.phase} ${styles.current}`}>3</span>
|
||||||
|
<span className={styles.phase}>4</span>
|
||||||
|
<span className={styles.phase}>5</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className={styles.experimentControls}>
|
||||||
|
<h3>Experiment Controls</h3>
|
||||||
|
<div className={styles.controlsButtons}>
|
||||||
|
{/*Pause button*/}
|
||||||
|
<button
|
||||||
|
className={`${!isPlaying ? styles.pausePlayActive : styles.pausePlayInactive}`}
|
||||||
|
onClick={() => {
|
||||||
|
setIsPlaying(false);
|
||||||
|
handleButton("pause");}
|
||||||
|
}
|
||||||
|
disabled={loading}
|
||||||
|
>❚❚</button>
|
||||||
|
|
||||||
|
{/*Play button*/}
|
||||||
|
<button
|
||||||
|
className={`${isPlaying ? styles.pausePlayActive : styles.pausePlayInactive}`}
|
||||||
|
onClick={() => {
|
||||||
|
setIsPlaying(true);
|
||||||
|
handleButton("play");}
|
||||||
|
}
|
||||||
|
disabled={loading}
|
||||||
|
>▶</button>
|
||||||
|
|
||||||
|
{/*Next button*/}
|
||||||
|
<button
|
||||||
|
className={styles.next}
|
||||||
|
onClick={() => handleButton("nextPhase")}
|
||||||
|
disabled={loading}
|
||||||
|
>
|
||||||
|
⏭
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{/*Restart Phase button*/}
|
||||||
|
<button
|
||||||
|
className={styles.restartPhase}
|
||||||
|
onClick={() => handleButton("resetPhase")}
|
||||||
|
disabled={loading}
|
||||||
|
>
|
||||||
|
↩
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{/*Restart Experiment button*/}
|
||||||
|
<button
|
||||||
|
className={styles.restartExperiment}
|
||||||
|
onClick={() => handleButton("resetExperiment")}
|
||||||
|
disabled={loading}
|
||||||
|
>
|
||||||
|
⟲
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className={styles.connectionStatus}>
|
||||||
|
{RobotConnected()}
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
{/* MAIN GRID */}
|
||||||
|
|
||||||
|
<main className={styles.phaseOverview}>
|
||||||
|
<section className={styles.phaseOverviewText}>
|
||||||
|
<h3>Phase Overview</h3>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<StatusList title="Goals" items={goals} type="goal" />
|
||||||
|
<StatusList title="Triggers" items={triggers} type="trigger" />
|
||||||
|
<StatusList title="Norms" items={norms} type="norm" />
|
||||||
|
<StatusList
|
||||||
|
title="Conditional Norms"
|
||||||
|
items={[{ id: 'cn_1', norm: '“RP is sad” - Be nice', achieved: false }]}
|
||||||
|
type="cond_norm"
|
||||||
|
/>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
{/* LOGS */}
|
||||||
|
<aside className={styles.logs}>
|
||||||
|
<h3>Logs</h3>
|
||||||
|
<div className={styles.logHeader}>
|
||||||
|
<span>Global:</span>
|
||||||
|
<button>ALL</button>
|
||||||
|
<button>Add</button>
|
||||||
|
<button className={styles.live}>Live</button>
|
||||||
|
</div>
|
||||||
|
<textarea defaultValue="Example Log: much log"></textarea>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
{/* FOOTER */}
|
||||||
|
<footer className={styles.controlsSection}>
|
||||||
|
<GestureControls />
|
||||||
|
<SpeechPresets />
|
||||||
|
<DirectSpeechInput />
|
||||||
|
</footer>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default MonitoringPage;
|
||||||
64
src/pages/MonitoringPage/MonitoringPageAPI.ts
Normal file
64
src/pages/MonitoringPage/MonitoringPageAPI.ts
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
const API_BASE = "http://localhost:8000/button_pressed"; // Change depending on Pims interup agent/ correct endpoint
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HELPER: Unified sender function
|
||||||
|
* In a real app, you might move this to a /services or /hooks folder
|
||||||
|
*/
|
||||||
|
const sendAPICall = async (type: string, context: string, endpoint?: string) => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${API_BASE}${endpoint ?? ""}`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ type, context }),
|
||||||
|
});
|
||||||
|
if (!response.ok) throw new Error("Backend response error");
|
||||||
|
console.log(`API Call send - Type: ${type}, Context: ${context} ${endpoint ? `, Endpoint: ${endpoint}` : ""}`);
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`Failed to send api call:`, err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sends an API call to the CB for going to the next phase.
|
||||||
|
* In case we can't go to the next phase, the function will throw an error.
|
||||||
|
*/
|
||||||
|
export async function nextPhase(): Promise<void> {
|
||||||
|
const type = "next_phase"
|
||||||
|
const context = ""
|
||||||
|
sendAPICall(type, context)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sends an API call to the CB for going to reset the currect phase
|
||||||
|
* In case we can't go to the next phase, the function will throw an error.
|
||||||
|
*/
|
||||||
|
export async function resetPhase(): Promise<void> {
|
||||||
|
const type = "reset_phase"
|
||||||
|
const context = ""
|
||||||
|
sendAPICall(type, context)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sends an API call to the CB for going to reset the experiment
|
||||||
|
* In case we can't go to the next phase, the function will throw an error.
|
||||||
|
*/
|
||||||
|
export async function resetExperiment(): Promise<void> {
|
||||||
|
const type = "reset_experiment"
|
||||||
|
const context = ""
|
||||||
|
sendAPICall(type, context)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function pauseExperiment(): Promise<void> {
|
||||||
|
const type = "pause"
|
||||||
|
const context = "true"
|
||||||
|
sendAPICall(type, context)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function playExperiment(): Promise<void> {
|
||||||
|
const type = "pause"
|
||||||
|
const context = "false"
|
||||||
|
sendAPICall(type, context)
|
||||||
|
}
|
||||||
167
src/pages/SimpleProgram/SimpleProgram.module.css
Normal file
167
src/pages/SimpleProgram/SimpleProgram.module.css
Normal file
@@ -0,0 +1,167 @@
|
|||||||
|
/* ---------- Layout ---------- */
|
||||||
|
|
||||||
|
.container {
|
||||||
|
height: 100%;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
background: #1e1e1e;
|
||||||
|
color: #f5f5f5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
padding: clamp(0.75rem, 2vw, 1.25rem);
|
||||||
|
background: #2a2a2a;
|
||||||
|
border-bottom: 1px solid #3a3a3a;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header h2 {
|
||||||
|
font-size: clamp(1rem, 2.2vw, 1.4rem);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.controls button {
|
||||||
|
margin-left: 0.5rem;
|
||||||
|
padding: 0.4rem 0.9rem;
|
||||||
|
border-radius: 6px;
|
||||||
|
border: none;
|
||||||
|
background: #111;
|
||||||
|
color: white;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.controls button:disabled {
|
||||||
|
opacity: 0.4;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Content ---------- */
|
||||||
|
|
||||||
|
.content {
|
||||||
|
flex: 1;
|
||||||
|
padding: 2%;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Grid ---------- */
|
||||||
|
|
||||||
|
.phaseGrid {
|
||||||
|
height: 100%;
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
grid-template-rows: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 2%;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Box ---------- */
|
||||||
|
|
||||||
|
.box {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
background: #ffffff;
|
||||||
|
color: #1e1e1e;
|
||||||
|
border-radius: 10px;
|
||||||
|
overflow: hidden;
|
||||||
|
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.25);
|
||||||
|
}
|
||||||
|
|
||||||
|
.boxHeader {
|
||||||
|
padding: 0.6rem 0.9rem;
|
||||||
|
background: linear-gradient(135deg, #dcdcdc, #e9e9e9);
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 500;
|
||||||
|
font-size: clamp(0.9rem, 1.5vw, 1.05rem);
|
||||||
|
border-bottom: 1px solid #cfcfcf;
|
||||||
|
}
|
||||||
|
|
||||||
|
.boxContent {
|
||||||
|
flex: 1;
|
||||||
|
padding: 0.8rem 1rem;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Lists ---------- */
|
||||||
|
|
||||||
|
.iconList {
|
||||||
|
list-style: none;
|
||||||
|
padding: 0;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.iconList li {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.6rem;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
font-size: clamp(0.85rem, 1.3vw, 1rem);
|
||||||
|
}
|
||||||
|
|
||||||
|
.bulletList {
|
||||||
|
margin: 0;
|
||||||
|
padding-left: 1.2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bulletList li {
|
||||||
|
margin-bottom: 0.4rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Icons ---------- */
|
||||||
|
|
||||||
|
.successIcon,
|
||||||
|
.failIcon {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
min-width: 1.5rem;
|
||||||
|
height: 1.5rem;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-weight: bold;
|
||||||
|
color: white;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.successIcon {
|
||||||
|
background: #3cb371;
|
||||||
|
}
|
||||||
|
|
||||||
|
.failIcon {
|
||||||
|
background: #e5533d;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Empty ---------- */
|
||||||
|
|
||||||
|
.empty {
|
||||||
|
opacity: 0.55;
|
||||||
|
font-style: italic;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Responsive ---------- */
|
||||||
|
|
||||||
|
@media (max-width: 900px) {
|
||||||
|
.phaseGrid {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
grid-template-rows: repeat(4, minmax(0, 1fr));
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.leftControls {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.backButton {
|
||||||
|
background: transparent;
|
||||||
|
border: 1px solid #555;
|
||||||
|
color: #ddd;
|
||||||
|
padding: 0.35rem 0.75rem;
|
||||||
|
border-radius: 6px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.backButton:hover {
|
||||||
|
background: #333;
|
||||||
|
}
|
||||||
192
src/pages/SimpleProgram/SimpleProgram.tsx
Normal file
192
src/pages/SimpleProgram/SimpleProgram.tsx
Normal file
@@ -0,0 +1,192 @@
|
|||||||
|
import React from "react";
|
||||||
|
import styles from "./SimpleProgram.module.css";
|
||||||
|
import useProgramStore from "../../utils/programStore.ts";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generic container box with a header and content area.
|
||||||
|
*/
|
||||||
|
type BoxProps = {
|
||||||
|
title: string;
|
||||||
|
children: React.ReactNode;
|
||||||
|
};
|
||||||
|
|
||||||
|
const Box: React.FC<BoxProps> = ({ title, children }) => (
|
||||||
|
<div className={styles.box}>
|
||||||
|
<div className={styles.boxHeader}>{title}</div>
|
||||||
|
<div className={styles.boxContent}>{children}</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renders a list of goals for a phase.
|
||||||
|
* Expects goal-like objects from the program store.
|
||||||
|
*/
|
||||||
|
const GoalList: React.FC<{ goals: unknown[] }> = ({ goals }) => {
|
||||||
|
if (!goals.length) {
|
||||||
|
return <p className={styles.empty}>No goals defined.</p>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ul className={styles.iconList}>
|
||||||
|
{goals.map((g, idx) => {
|
||||||
|
const goal = g as {
|
||||||
|
id?: string;
|
||||||
|
description?: string;
|
||||||
|
achieved?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<li key={goal.id ?? idx}>
|
||||||
|
<span
|
||||||
|
className={
|
||||||
|
goal.achieved ? styles.successIcon : styles.failIcon
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{goal.achieved ? "✔" : "✖"}
|
||||||
|
</span>
|
||||||
|
{goal.description ?? "Unnamed goal"}
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renders a list of triggers for a phase.
|
||||||
|
*/
|
||||||
|
const TriggerList: React.FC<{ triggers: unknown[] }> = ({ triggers }) => {
|
||||||
|
if (!triggers.length) {
|
||||||
|
return <p className={styles.empty}>No triggers defined.</p>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ul className={styles.iconList}>
|
||||||
|
{triggers.map((t, idx) => {
|
||||||
|
const trigger = t as {
|
||||||
|
id?: string;
|
||||||
|
label?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<li key={trigger.id ?? idx}>
|
||||||
|
<span className={styles.failIcon}>✖</span>
|
||||||
|
{trigger.label ?? "Unnamed trigger"}
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renders a list of norms for a phase.
|
||||||
|
*/
|
||||||
|
const NormList: React.FC<{ norms: unknown[] }> = ({ norms }) => {
|
||||||
|
if (!norms.length) {
|
||||||
|
return <p className={styles.empty}>No norms defined.</p>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ul className={styles.bulletList}>
|
||||||
|
{norms.map((n, idx) => {
|
||||||
|
const norm = n as {
|
||||||
|
id?: string;
|
||||||
|
norm?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
return <li key={norm.id ?? idx}>{norm.norm ?? "Unnamed norm"}</li>;
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Displays all phase-related information in a grid layout.
|
||||||
|
*/
|
||||||
|
type PhaseGridProps = {
|
||||||
|
norms: unknown[];
|
||||||
|
goals: unknown[];
|
||||||
|
triggers: unknown[];
|
||||||
|
};
|
||||||
|
|
||||||
|
const PhaseGrid: React.FC<PhaseGridProps> = ({
|
||||||
|
norms,
|
||||||
|
goals,
|
||||||
|
triggers,
|
||||||
|
}) => (
|
||||||
|
<div className={styles.phaseGrid}>
|
||||||
|
<Box title="Norms">
|
||||||
|
<NormList norms={norms} />
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box title="Triggers">
|
||||||
|
<TriggerList triggers={triggers} />
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box title="Goals">
|
||||||
|
<GoalList goals={goals} />
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box title="Conditional Norms">
|
||||||
|
<p className={styles.empty}>No conditional norms defined.</p>
|
||||||
|
</Box>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Main program viewer.
|
||||||
|
* Reads all data from the program store and allows
|
||||||
|
* navigating between phases.
|
||||||
|
*/
|
||||||
|
const SimpleProgram: React.FC = () => {
|
||||||
|
const getPhaseIds = useProgramStore((s) => s.getPhaseIds);
|
||||||
|
const getNormsInPhase = useProgramStore((s) => s.getNormsInPhase);
|
||||||
|
const getGoalsInPhase = useProgramStore((s) => s.getGoalsInPhase);
|
||||||
|
const getTriggersInPhase = useProgramStore((s) => s.getTriggersInPhase);
|
||||||
|
|
||||||
|
const phaseIds = getPhaseIds();
|
||||||
|
const [phaseIndex, setPhaseIndex] = React.useState(0);
|
||||||
|
|
||||||
|
if (phaseIds.length === 0) {
|
||||||
|
return <p className={styles.empty}>No program loaded.</p>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const phaseId = phaseIds[phaseIndex];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={styles.container}>
|
||||||
|
<header className={styles.header}>
|
||||||
|
<h2>
|
||||||
|
Phase {phaseIndex + 1} / {phaseIds.length}
|
||||||
|
</h2>
|
||||||
|
|
||||||
|
<div className={styles.controls}>
|
||||||
|
<button
|
||||||
|
disabled={phaseIndex === 0}
|
||||||
|
onClick={() => setPhaseIndex((i) => i - 1)}
|
||||||
|
>
|
||||||
|
◀ Prev
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
disabled={phaseIndex === phaseIds.length - 1}
|
||||||
|
onClick={() => setPhaseIndex((i) => i + 1)}
|
||||||
|
>
|
||||||
|
Next ▶
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div className={styles.content}>
|
||||||
|
<PhaseGrid
|
||||||
|
norms={getNormsInPhase(phaseId)}
|
||||||
|
goals={getGoalsInPhase(phaseId)}
|
||||||
|
triggers={getTriggersInPhase(phaseId)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default SimpleProgram;
|
||||||
@@ -127,3 +127,9 @@
|
|||||||
filter: drop-shadow(0 0 0.25rem red);
|
filter: drop-shadow(0 0 0.25rem red);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.backButton {
|
||||||
|
background: var(--bg-surface);
|
||||||
|
box-shadow: var(--panel-shadow);
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
margin-left: 0.5rem;
|
||||||
|
}
|
||||||
@@ -7,13 +7,16 @@ import {
|
|||||||
MarkerType,
|
MarkerType,
|
||||||
} from '@xyflow/react';
|
} from '@xyflow/react';
|
||||||
import '@xyflow/react/dist/style.css';
|
import '@xyflow/react/dist/style.css';
|
||||||
import {useEffect} from "react";
|
import {useEffect, useState} from "react";
|
||||||
import {useShallow} from 'zustand/react/shallow';
|
import {useShallow} from 'zustand/react/shallow';
|
||||||
|
import useProgramStore from "../../utils/programStore.ts";
|
||||||
import {DndToolbar} from './visualProgrammingUI/components/DragDropSidebar.tsx';
|
import {DndToolbar} from './visualProgrammingUI/components/DragDropSidebar.tsx';
|
||||||
import useFlowStore from './visualProgrammingUI/VisProgStores.tsx';
|
import useFlowStore from './visualProgrammingUI/VisProgStores.tsx';
|
||||||
import type {FlowState} from './visualProgrammingUI/VisProgTypes.tsx';
|
import type {FlowState} from './visualProgrammingUI/VisProgTypes.tsx';
|
||||||
import styles from './VisProg.module.css'
|
import styles from './VisProg.module.css'
|
||||||
import { NodeReduces, NodeTypes } from './visualProgrammingUI/NodeRegistry.ts';
|
import { NodeReduces, NodeTypes } from './visualProgrammingUI/NodeRegistry.ts';
|
||||||
|
import SaveLoadPanel from './visualProgrammingUI/components/SaveLoadPanel.tsx';
|
||||||
|
import MonitoringPage from '../MonitoringPage/MonitoringPage.tsx';
|
||||||
|
|
||||||
// --| config starting params for flow |--
|
// --| config starting params for flow |--
|
||||||
|
|
||||||
@@ -38,6 +41,7 @@ const selector = (state: FlowState) => ({
|
|||||||
nodes: state.nodes,
|
nodes: state.nodes,
|
||||||
edges: state.edges,
|
edges: state.edges,
|
||||||
onNodesChange: state.onNodesChange,
|
onNodesChange: state.onNodesChange,
|
||||||
|
onEdgesDelete: state.onEdgesDelete,
|
||||||
onEdgesChange: state.onEdgesChange,
|
onEdgesChange: state.onEdgesChange,
|
||||||
onConnect: state.onConnect,
|
onConnect: state.onConnect,
|
||||||
onReconnectStart: state.onReconnectStart,
|
onReconnectStart: state.onReconnectStart,
|
||||||
@@ -61,6 +65,7 @@ const VisProgUI = () => {
|
|||||||
const {
|
const {
|
||||||
nodes, edges,
|
nodes, edges,
|
||||||
onNodesChange,
|
onNodesChange,
|
||||||
|
onEdgesDelete,
|
||||||
onEdgesChange,
|
onEdgesChange,
|
||||||
onConnect,
|
onConnect,
|
||||||
onReconnect,
|
onReconnect,
|
||||||
@@ -90,6 +95,7 @@ const VisProgUI = () => {
|
|||||||
defaultEdgeOptions={DEFAULT_EDGE_OPTIONS}
|
defaultEdgeOptions={DEFAULT_EDGE_OPTIONS}
|
||||||
nodeTypes={NodeTypes}
|
nodeTypes={NodeTypes}
|
||||||
onNodesChange={onNodesChange}
|
onNodesChange={onNodesChange}
|
||||||
|
onEdgesDelete={onEdgesDelete}
|
||||||
onEdgesChange={onEdgesChange}
|
onEdgesChange={onEdgesChange}
|
||||||
onReconnect={onReconnect}
|
onReconnect={onReconnect}
|
||||||
onReconnectStart={onReconnectStart}
|
onReconnectStart={onReconnectStart}
|
||||||
@@ -103,7 +109,10 @@ const VisProgUI = () => {
|
|||||||
>
|
>
|
||||||
<Panel position="top-center" className={styles.dndPanel}>
|
<Panel position="top-center" className={styles.dndPanel}>
|
||||||
<DndToolbar/> {/* contains the drag and drop panel for nodes */}
|
<DndToolbar/> {/* contains the drag and drop panel for nodes */}
|
||||||
</Panel>
|
</Panel>
|
||||||
|
<Panel position = "bottom-left" className={styles.saveLoadPanel}>
|
||||||
|
<SaveLoadPanel></SaveLoadPanel>
|
||||||
|
</Panel>
|
||||||
<Panel position="bottom-center">
|
<Panel position="bottom-center">
|
||||||
<button onClick={() => undo()}>undo</button>
|
<button onClick={() => undo()}>undo</button>
|
||||||
<button onClick={() => redo()}>Redo</button>
|
<button onClick={() => redo()}>Redo</button>
|
||||||
@@ -131,7 +140,7 @@ function VisualProgrammingUI() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// currently outputs the prepared program to the console
|
// currently outputs the prepared program to the console
|
||||||
function runProgram() {
|
function runProgramm() {
|
||||||
const phases = graphReducer();
|
const phases = graphReducer();
|
||||||
const program = {phases}
|
const program = {phases}
|
||||||
console.log(JSON.stringify(program, null, 2));
|
console.log(JSON.stringify(program, null, 2));
|
||||||
@@ -145,6 +154,10 @@ function runProgram() {
|
|||||||
).then((res) => {
|
).then((res) => {
|
||||||
if (!res.ok) throw new Error("Failed communicating with the backend.")
|
if (!res.ok) throw new Error("Failed communicating with the backend.")
|
||||||
console.log("Successfully sent the program to the backend.");
|
console.log("Successfully sent the program to the backend.");
|
||||||
|
|
||||||
|
// store reduced program in global program store for further use in the UI
|
||||||
|
// when the program was sent to the backend successfully:
|
||||||
|
useProgramStore.getState().setProgramState(structuredClone(program));
|
||||||
}).catch(() => console.log("Failed to send program to the backend."));
|
}).catch(() => console.log("Failed to send program to the backend."));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -167,6 +180,27 @@ function graphReducer() {
|
|||||||
* @constructor
|
* @constructor
|
||||||
*/
|
*/
|
||||||
function VisProgPage() {
|
function VisProgPage() {
|
||||||
|
const [showSimpleProgram, setShowSimpleProgram] = useState(false);
|
||||||
|
const setProgramState = useProgramStore((state) => state.setProgramState);
|
||||||
|
|
||||||
|
const runProgram = () => {
|
||||||
|
const phases = graphReducer(); // reduce graph
|
||||||
|
setProgramState({ phases }); // <-- save to store
|
||||||
|
setShowSimpleProgram(true); // show SimpleProgram
|
||||||
|
runProgramm(); // send to backend if needed
|
||||||
|
};
|
||||||
|
|
||||||
|
if (showSimpleProgram) {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<button className={styles.backButton} onClick={() => setShowSimpleProgram(false)}>
|
||||||
|
Back to Editor ◀
|
||||||
|
</button>
|
||||||
|
<MonitoringPage/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<VisualProgrammingUI/>
|
<VisualProgrammingUI/>
|
||||||
|
|||||||
@@ -1,14 +1,50 @@
|
|||||||
import StartNode, { StartConnects, StartReduce } from "./nodes/StartNode";
|
import EndNode, {
|
||||||
import EndNode, { EndConnects, EndReduce } from "./nodes/EndNode";
|
EndConnectionTarget,
|
||||||
import PhaseNode, { PhaseConnects, PhaseReduce } from "./nodes/PhaseNode";
|
EndConnectionSource,
|
||||||
import NormNode, { NormConnects, NormReduce } from "./nodes/NormNode";
|
EndDisconnectionTarget,
|
||||||
|
EndDisconnectionSource,
|
||||||
|
EndReduce
|
||||||
|
} from "./nodes/EndNode";
|
||||||
import { EndNodeDefaults } from "./nodes/EndNode.default";
|
import { EndNodeDefaults } from "./nodes/EndNode.default";
|
||||||
|
import StartNode, {
|
||||||
|
StartConnectionTarget,
|
||||||
|
StartConnectionSource,
|
||||||
|
StartDisconnectionTarget,
|
||||||
|
StartDisconnectionSource,
|
||||||
|
StartReduce
|
||||||
|
} from "./nodes/StartNode";
|
||||||
import { StartNodeDefaults } from "./nodes/StartNode.default";
|
import { StartNodeDefaults } from "./nodes/StartNode.default";
|
||||||
|
import PhaseNode, {
|
||||||
|
PhaseConnectionTarget,
|
||||||
|
PhaseConnectionSource,
|
||||||
|
PhaseDisconnectionTarget,
|
||||||
|
PhaseDisconnectionSource,
|
||||||
|
PhaseReduce
|
||||||
|
} from "./nodes/PhaseNode";
|
||||||
import { PhaseNodeDefaults } from "./nodes/PhaseNode.default";
|
import { PhaseNodeDefaults } from "./nodes/PhaseNode.default";
|
||||||
|
import NormNode, {
|
||||||
|
NormConnectionTarget,
|
||||||
|
NormConnectionSource,
|
||||||
|
NormDisconnectionTarget,
|
||||||
|
NormDisconnectionSource,
|
||||||
|
NormReduce
|
||||||
|
} from "./nodes/NormNode";
|
||||||
import { NormNodeDefaults } from "./nodes/NormNode.default";
|
import { NormNodeDefaults } from "./nodes/NormNode.default";
|
||||||
import GoalNode, { GoalConnects, GoalReduce } from "./nodes/GoalNode";
|
import GoalNode, {
|
||||||
|
GoalConnectionTarget,
|
||||||
|
GoalConnectionSource,
|
||||||
|
GoalDisconnectionTarget,
|
||||||
|
GoalDisconnectionSource,
|
||||||
|
GoalReduce
|
||||||
|
} from "./nodes/GoalNode";
|
||||||
import { GoalNodeDefaults } from "./nodes/GoalNode.default";
|
import { GoalNodeDefaults } from "./nodes/GoalNode.default";
|
||||||
import TriggerNode, { TriggerConnects, TriggerReduce } from "./nodes/TriggerNode";
|
import TriggerNode, {
|
||||||
|
TriggerConnectionTarget,
|
||||||
|
TriggerConnectionSource,
|
||||||
|
TriggerDisconnectionTarget,
|
||||||
|
TriggerDisconnectionSource,
|
||||||
|
TriggerReduce
|
||||||
|
} from "./nodes/TriggerNode";
|
||||||
import { TriggerNodeDefaults } from "./nodes/TriggerNode.default";
|
import { TriggerNodeDefaults } from "./nodes/TriggerNode.default";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -60,15 +96,51 @@ export const NodeReduces = {
|
|||||||
/**
|
/**
|
||||||
* Connection functions for each node type.
|
* Connection functions for each node type.
|
||||||
*
|
*
|
||||||
* These functions define how nodes of a particular type can connect to other nodes.
|
* These functions define any additional actions a node may perform
|
||||||
|
* when a new connection is made
|
||||||
*/
|
*/
|
||||||
export const NodeConnects = {
|
export const NodeConnections = {
|
||||||
start: StartConnects,
|
Targets: {
|
||||||
end: EndConnects,
|
start: StartConnectionTarget,
|
||||||
phase: PhaseConnects,
|
end: EndConnectionTarget,
|
||||||
norm: NormConnects,
|
phase: PhaseConnectionTarget,
|
||||||
goal: GoalConnects,
|
norm: NormConnectionTarget,
|
||||||
trigger: TriggerConnects,
|
goal: GoalConnectionTarget,
|
||||||
|
trigger: TriggerConnectionTarget,
|
||||||
|
},
|
||||||
|
Sources: {
|
||||||
|
start: StartConnectionSource,
|
||||||
|
end: EndConnectionSource,
|
||||||
|
phase: PhaseConnectionSource,
|
||||||
|
norm: NormConnectionSource,
|
||||||
|
goal: GoalConnectionSource,
|
||||||
|
trigger: TriggerConnectionSource,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Disconnection functions for each node type.
|
||||||
|
*
|
||||||
|
* These functions define any additional actions a node may perform
|
||||||
|
* when a connection is disconnected
|
||||||
|
*/
|
||||||
|
export const NodeDisconnections = {
|
||||||
|
Targets: {
|
||||||
|
start: StartDisconnectionTarget,
|
||||||
|
end: EndDisconnectionTarget,
|
||||||
|
phase: PhaseDisconnectionTarget,
|
||||||
|
norm: NormDisconnectionTarget,
|
||||||
|
goal: GoalDisconnectionTarget,
|
||||||
|
trigger: TriggerDisconnectionTarget,
|
||||||
|
},
|
||||||
|
Sources: {
|
||||||
|
start: StartDisconnectionSource,
|
||||||
|
end: EndDisconnectionSource,
|
||||||
|
phase: PhaseDisconnectionSource,
|
||||||
|
norm: NormDisconnectionSource,
|
||||||
|
goal: GoalDisconnectionSource,
|
||||||
|
trigger: TriggerDisconnectionSource,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -9,7 +9,12 @@ import {
|
|||||||
type XYPosition,
|
type XYPosition,
|
||||||
} from '@xyflow/react';
|
} from '@xyflow/react';
|
||||||
import type { FlowState } from './VisProgTypes';
|
import type { FlowState } from './VisProgTypes';
|
||||||
import { NodeDefaults, NodeConnects, NodeDeletes } from './NodeRegistry';
|
import {
|
||||||
|
NodeDefaults,
|
||||||
|
NodeConnections as NodeCs,
|
||||||
|
NodeDisconnections as NodeDs,
|
||||||
|
NodeDeletes
|
||||||
|
} from './NodeRegistry';
|
||||||
import { UndoRedo } from "./EditorUndoRedo.ts";
|
import { UndoRedo } from "./EditorUndoRedo.ts";
|
||||||
|
|
||||||
|
|
||||||
@@ -40,7 +45,7 @@ const initialNodes : Node[] = [
|
|||||||
createNode('start', 'start', {x: 100, y: 100}, {label: "Start"}, false),
|
createNode('start', 'start', {x: 100, y: 100}, {label: "Start"}, false),
|
||||||
createNode('end', 'end', {x: 500, y: 100}, {label: "End"}, false),
|
createNode('end', 'end', {x: 500, y: 100}, {label: "End"}, false),
|
||||||
createNode('phase-1', 'phase', {x:200, y:100}, {label: "Phase 1", children : []}),
|
createNode('phase-1', 'phase', {x:200, y:100}, {label: "Phase 1", children : []}),
|
||||||
createNode('norms-1', 'norm', {x:-200, y:100}, {label: "Initial Norms", normList: ["Be a robot", "get good"]}),
|
createNode('norms-1', 'norm', {x:-200, y:100}, {label: "Initial Norms", normList: ["Be a robot", "get good"], critical:false}),
|
||||||
];
|
];
|
||||||
|
|
||||||
// * Initial edges * /
|
// * Initial edges * /
|
||||||
@@ -71,10 +76,25 @@ const useFlowStore = create<FlowState>(UndoRedo((set, get) => ({
|
|||||||
*/
|
*/
|
||||||
onNodesChange: (changes) => set({nodes: applyNodeChanges(changes, get().nodes)}),
|
onNodesChange: (changes) => set({nodes: applyNodeChanges(changes, get().nodes)}),
|
||||||
|
|
||||||
|
onEdgesDelete: (edges) => {
|
||||||
|
|
||||||
|
// we make sure any affected nodes get updated to reflect removal of edges
|
||||||
|
edges.forEach((edge) => {
|
||||||
|
const nodes = get().nodes;
|
||||||
|
|
||||||
|
const sourceNode = nodes.find((n) => n.id == edge.source);
|
||||||
|
const targetNode = nodes.find((n) => n.id == edge.target);
|
||||||
|
|
||||||
|
if (sourceNode) { NodeDs.Sources[sourceNode.type as keyof typeof NodeDs.Sources](sourceNode, edge.target); }
|
||||||
|
if (targetNode) { NodeDs.Targets[targetNode.type as keyof typeof NodeDs.Targets](targetNode, edge.source); }
|
||||||
|
});
|
||||||
|
},
|
||||||
/**
|
/**
|
||||||
* Handles changes to edges triggered by ReactFlow.
|
* Handles changes to edges triggered by ReactFlow.
|
||||||
*/
|
*/
|
||||||
onEdgesChange: (changes) => set({ edges: applyEdgeChanges(changes, get().edges) }),
|
onEdgesChange: (changes) => {
|
||||||
|
set({ edges: applyEdgeChanges(changes, get().edges) })
|
||||||
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handles creating a new connection between nodes.
|
* Handles creating a new connection between nodes.
|
||||||
@@ -82,32 +102,16 @@ const useFlowStore = create<FlowState>(UndoRedo((set, get) => ({
|
|||||||
*/
|
*/
|
||||||
onConnect: (connection) => {
|
onConnect: (connection) => {
|
||||||
get().pushSnapshot();
|
get().pushSnapshot();
|
||||||
|
set({edges: addEdge(connection, get().edges)});
|
||||||
|
|
||||||
const edges = addEdge(connection, get().edges);
|
// We make sure to perform any required data updates on the newly connected nodes
|
||||||
const nodes = get().nodes;
|
const nodes = get().nodes;
|
||||||
// connection has: { source, sourceHandle, target, targetHandle }
|
|
||||||
// Let's find the source and target ID's.
|
|
||||||
const sourceNode = nodes.find((n) => n.id == connection.source);
|
const sourceNode = nodes.find((n) => n.id == connection.source);
|
||||||
const targetNode = nodes.find((n) => n.id == connection.target);
|
const targetNode = nodes.find((n) => n.id == connection.target);
|
||||||
|
|
||||||
// In case the nodes weren't found, return basic functionality.
|
if (sourceNode) { NodeCs.Sources[sourceNode.type as keyof typeof NodeCs.Sources](sourceNode, connection.target); }
|
||||||
if ( sourceNode == undefined
|
if (targetNode) { NodeCs.Targets[targetNode.type as keyof typeof NodeCs.Targets](targetNode, connection.source); }
|
||||||
|| targetNode == undefined
|
|
||||||
|| sourceNode.type == undefined
|
|
||||||
|| targetNode.type == undefined
|
|
||||||
){
|
|
||||||
set({ nodes, edges });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// We should find out how their data changes by calling their respective functions.
|
|
||||||
const sourceConnectFunction = NodeConnects[sourceNode.type as keyof typeof NodeConnects]
|
|
||||||
const targetConnectFunction = NodeConnects[targetNode.type as keyof typeof NodeConnects]
|
|
||||||
|
|
||||||
// We're going to have to update their data based on how they want to update it.
|
|
||||||
sourceConnectFunction(sourceNode, targetNode, true)
|
|
||||||
targetConnectFunction(targetNode, sourceNode, false)
|
|
||||||
set({ nodes, edges });
|
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -116,6 +120,22 @@ const useFlowStore = create<FlowState>(UndoRedo((set, get) => ({
|
|||||||
onReconnect: (oldEdge, newConnection) => {
|
onReconnect: (oldEdge, newConnection) => {
|
||||||
get().edgeReconnectSuccessful = true;
|
get().edgeReconnectSuccessful = true;
|
||||||
set({ edges: reconnectEdge(oldEdge, newConnection, get().edges) });
|
set({ edges: reconnectEdge(oldEdge, newConnection, get().edges) });
|
||||||
|
|
||||||
|
// We make sure to perform any required data updates on the newly reconnected nodes
|
||||||
|
const nodes = get().nodes;
|
||||||
|
|
||||||
|
const oldSourceNode = nodes.find((n) => n.id == oldEdge.source)!;
|
||||||
|
const oldTargetNode = nodes.find((n) => n.id == oldEdge.target)!;
|
||||||
|
const newSourceNode = nodes.find((n) => n.id == newConnection.source)!;
|
||||||
|
const newTargetNode = nodes.find((n) => n.id == newConnection.target)!;
|
||||||
|
|
||||||
|
if (oldSourceNode === newSourceNode && oldTargetNode === newTargetNode) return;
|
||||||
|
|
||||||
|
NodeCs.Sources[newSourceNode.type as keyof typeof NodeCs.Sources](newSourceNode, newConnection.target);
|
||||||
|
NodeCs.Targets[newTargetNode.type as keyof typeof NodeCs.Targets](newTargetNode, newConnection.source);
|
||||||
|
|
||||||
|
NodeDs.Sources[oldSourceNode.type as keyof typeof NodeDs.Sources](oldSourceNode, oldEdge.target);
|
||||||
|
NodeDs.Targets[oldTargetNode.type as keyof typeof NodeDs.Targets](oldTargetNode, oldEdge.source);
|
||||||
},
|
},
|
||||||
|
|
||||||
onReconnectStart: () => {
|
onReconnectStart: () => {
|
||||||
@@ -128,11 +148,21 @@ const useFlowStore = create<FlowState>(UndoRedo((set, get) => ({
|
|||||||
* if it is not reconnected to a node after detaching it
|
* if it is not reconnected to a node after detaching it
|
||||||
*
|
*
|
||||||
* @param _evt - the event
|
* @param _evt - the event
|
||||||
* @param {{id: string}} edge - the described edge
|
* @param edge - the described edge
|
||||||
*/
|
*/
|
||||||
onReconnectEnd: (_evt, edge) => {
|
onReconnectEnd: (_evt, edge) => {
|
||||||
if (!get().edgeReconnectSuccessful) {
|
if (!get().edgeReconnectSuccessful) {
|
||||||
|
// delete the edge from the flowState
|
||||||
set({ edges: get().edges.filter((e) => e.id !== edge.id) });
|
set({ edges: get().edges.filter((e) => e.id !== edge.id) });
|
||||||
|
|
||||||
|
// update node data to reflect the dropped edge
|
||||||
|
const nodes = get().nodes;
|
||||||
|
|
||||||
|
const sourceNode = nodes.find((n) => n.id == edge.source)!;
|
||||||
|
const targetNode = nodes.find((n) => n.id == edge.target)!;
|
||||||
|
|
||||||
|
NodeDs.Sources[sourceNode.type as keyof typeof NodeDs.Sources](sourceNode, edge.target);
|
||||||
|
NodeDs.Targets[targetNode.type as keyof typeof NodeDs.Targets](targetNode, edge.source);
|
||||||
}
|
}
|
||||||
set({ edgeReconnectSuccessful: true });
|
set({ edgeReconnectSuccessful: true });
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
// VisProgTypes.ts
|
// VisProgTypes.ts
|
||||||
import type { Edge, OnNodesChange, OnEdgesChange, OnConnect, OnReconnect, Node } from '@xyflow/react';
|
import type {Edge, OnNodesChange, OnEdgesChange, OnConnect, OnReconnect, Node, OnEdgesDelete} from '@xyflow/react';
|
||||||
import type { NodeTypes } from './NodeRegistry';
|
import type { NodeTypes } from './NodeRegistry';
|
||||||
import type {FlowSnapshot} from "./EditorUndoRedo.ts";
|
import type {FlowSnapshot} from "./EditorUndoRedo.ts";
|
||||||
|
|
||||||
@@ -27,6 +27,8 @@ export type FlowState = {
|
|||||||
/** Handler for changes to nodes triggered by ReactFlow */
|
/** Handler for changes to nodes triggered by ReactFlow */
|
||||||
onNodesChange: OnNodesChange;
|
onNodesChange: OnNodesChange;
|
||||||
|
|
||||||
|
onEdgesDelete: OnEdgesDelete;
|
||||||
|
|
||||||
/** Handler for changes to edges triggered by ReactFlow */
|
/** Handler for changes to edges triggered by ReactFlow */
|
||||||
onEdgesChange: OnEdgesChange;
|
onEdgesChange: OnEdgesChange;
|
||||||
|
|
||||||
@@ -44,7 +46,7 @@ export type FlowState = {
|
|||||||
* @param _ - event or unused parameter
|
* @param _ - event or unused parameter
|
||||||
* @param edge - the edge that finished reconnecting
|
* @param edge - the edge that finished reconnecting
|
||||||
*/
|
*/
|
||||||
onReconnectEnd: (_: unknown, edge: { id: string }) => void;
|
onReconnectEnd: (_: unknown, edge: Edge) => void;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Deletes a node and any connected edges.
|
* Deletes a node and any connected edges.
|
||||||
|
|||||||
@@ -92,7 +92,7 @@ function addNodeToFlow(nodeType: keyof typeof NodeTypes, position: XYPosition) {
|
|||||||
id: id,
|
id: id,
|
||||||
type: nodeType,
|
type: nodeType,
|
||||||
position,
|
position,
|
||||||
data: {...defaultData}
|
data: JSON.parse(JSON.stringify(defaultData))
|
||||||
}
|
}
|
||||||
addNode(newNode);
|
addNode(newNode);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
.save-load-panel {
|
||||||
|
border-radius: 0 0 5pt 5pt;
|
||||||
|
background-color: canvas;
|
||||||
|
}
|
||||||
|
|
||||||
|
label.file-input-button {
|
||||||
|
cursor: pointer;
|
||||||
|
outline: forestgreen solid 2pt;
|
||||||
|
filter: drop-shadow(0 0 0.25rem forestgreen);
|
||||||
|
transition: filter 200ms;
|
||||||
|
|
||||||
|
input[type="file"] {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
filter: drop-shadow(0 0 0.5rem forestgreen);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.save-button {
|
||||||
|
text-decoration: none;
|
||||||
|
outline: dodgerblue solid 2pt;
|
||||||
|
filter: drop-shadow(0 0 0.25rem dodgerblue);
|
||||||
|
transition: filter 200ms;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
filter: drop-shadow(0 0 0.5rem dodgerblue);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import {type ChangeEvent, useRef, useState} from "react";
|
||||||
|
import useFlowStore from "../VisProgStores";
|
||||||
|
import visProgStyles from "../../VisProg.module.css";
|
||||||
|
import styles from "./SaveLoadPanel.module.css";
|
||||||
|
import { makeProjectBlob, type SavedProject } from "../../../../utils/SaveLoad";
|
||||||
|
|
||||||
|
export default function SaveLoadPanel() {
|
||||||
|
const nodes = useFlowStore((s) => s.nodes);
|
||||||
|
const edges = useFlowStore((s) => s.edges);
|
||||||
|
const setNodes = useFlowStore((s) => s.setNodes);
|
||||||
|
const setEdges = useFlowStore((s) => s.setEdges);
|
||||||
|
|
||||||
|
const [saveUrl, setSaveUrl] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// ref to the file input
|
||||||
|
const inputRef = useRef<HTMLInputElement | null>(null);
|
||||||
|
|
||||||
|
const onSave = async (nameGuess = "visual-program") => {
|
||||||
|
const blob = makeProjectBlob(nameGuess, nodes, edges);
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
setSaveUrl(url);
|
||||||
|
};
|
||||||
|
|
||||||
|
// input change handler updates the graph with a parsed JSON file
|
||||||
|
const handleFileChange = async (e: ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const file = e.target.files?.[0];
|
||||||
|
if (!file) return;
|
||||||
|
try {
|
||||||
|
const text = await file.text();
|
||||||
|
const parsed = JSON.parse(text) as SavedProject;
|
||||||
|
if (!parsed.nodes || !parsed.edges) throw new Error("Invalid file format");
|
||||||
|
setNodes(parsed.nodes);
|
||||||
|
setEdges(parsed.edges);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
alert("Loading failed. See console.");
|
||||||
|
} finally {
|
||||||
|
// allow re-selecting same file next time
|
||||||
|
if (inputRef.current) inputRef.current.value = "";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const defaultName = "visual-program";
|
||||||
|
return (
|
||||||
|
<div className={`flex-col gap-lg padding-md border-lg ${styles.saveLoadPanel}`}>
|
||||||
|
<div className="description">You can save and load your graph here.</div>
|
||||||
|
<div className={`flex-row gap-lg justify-center`}>
|
||||||
|
<a
|
||||||
|
href={saveUrl ?? "#"}
|
||||||
|
onClick={() => onSave(defaultName)}
|
||||||
|
download={`${defaultName}.json`}
|
||||||
|
className={`${visProgStyles.draggableNode} ${styles.saveButton}`}
|
||||||
|
>
|
||||||
|
Save Graph
|
||||||
|
</a>
|
||||||
|
|
||||||
|
<label className={`${visProgStyles.draggableNode} ${styles.fileInputButton}`}>
|
||||||
|
<input
|
||||||
|
ref={inputRef}
|
||||||
|
type="file"
|
||||||
|
accept=".visprog.json,.json,.txt,application/json,text/plain"
|
||||||
|
onChange={handleFileChange}
|
||||||
|
/>
|
||||||
|
Load Graph
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -5,7 +5,8 @@ import {
|
|||||||
type Node,
|
type Node,
|
||||||
} from '@xyflow/react';
|
} from '@xyflow/react';
|
||||||
import { Toolbar } from '../components/NodeComponents';
|
import { Toolbar } from '../components/NodeComponents';
|
||||||
import styles from '../../VisProg.module.css';
|
import styles from '../../VisProg.module.css';
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The typing of this node's data
|
* The typing of this node's data
|
||||||
@@ -51,10 +52,37 @@ export function EndReduce(node: Node, _nodes: Node[]) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Any connection functionality that should get called when a connection is made to this node type (end)
|
* This function is called whenever a connection is made with this node type as the target
|
||||||
* @param _thisNode the node of which the functionality gets called
|
* @param _thisNode the node of this node type which function is called
|
||||||
* @param _otherNode the other node which has connected
|
* @param _sourceNodeId the source of the received connection
|
||||||
* @param _isThisSource whether this node is the one that is the source of the connection
|
|
||||||
*/
|
*/
|
||||||
export function EndConnects(_thisNode: Node, _otherNode: Node, _isThisSource: boolean) {
|
export function EndConnectionTarget(_thisNode: Node, _sourceNodeId: string) {
|
||||||
|
// no additional connection logic exists yet
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This function is called whenever a connection is made with this node type as the source
|
||||||
|
* @param _thisNode the node of this node type which function is called
|
||||||
|
* @param _targetNodeId the target of the created connection
|
||||||
|
*/
|
||||||
|
export function EndConnectionSource(_thisNode: Node, _targetNodeId: string) {
|
||||||
|
// no additional connection logic exists yet
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This function is called whenever a connection is disconnected with this node type as the target
|
||||||
|
* @param _thisNode the node of this node type which function is called
|
||||||
|
* @param _sourceNodeId the source of the disconnected connection
|
||||||
|
*/
|
||||||
|
export function EndDisconnectionTarget(_thisNode: Node, _sourceNodeId: string) {
|
||||||
|
// no additional connection logic exists yet
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This function is called whenever a connection is disconnected with this node type as the source
|
||||||
|
* @param _thisNode the node of this node type which function is called
|
||||||
|
* @param _targetNodeId the target of the diconnected connection
|
||||||
|
*/
|
||||||
|
export function EndDisconnectionSource(_thisNode: Node, _targetNodeId: string) {
|
||||||
|
// no additional connection logic exists yet
|
||||||
}
|
}
|
||||||
@@ -75,8 +75,8 @@ export default function GoalNode({id, data}: NodeProps<GoalNode>) {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Reduces each Goal, including its children down into its relevant data.
|
* Reduces each Goal, including its children down into its relevant data.
|
||||||
* @param node: The Node Properties of this node.
|
* @param node The Node Properties of this node.
|
||||||
* @param _nodes: all the nodes in the graph
|
* @param _nodes all the nodes in the graph
|
||||||
*/
|
*/
|
||||||
export function GoalReduce(node: Node, _nodes: Node[]) {
|
export function GoalReduce(node: Node, _nodes: Node[]) {
|
||||||
const data = node.data as GoalNodeData;
|
const data = node.data as GoalNodeData;
|
||||||
@@ -89,11 +89,37 @@ export function GoalReduce(node: Node, _nodes: Node[]) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This function is called whenever a connection is made with this node type (Goal)
|
* This function is called whenever a connection is made with this node type as the target
|
||||||
* @param _thisNode the node of this node type which function is called
|
* @param _thisNode the node of this node type which function is called
|
||||||
* @param _otherNode the other node which was part of the connection
|
* @param _sourceNodeId the source of the received connection
|
||||||
* @param _isThisSource whether this instance of the node was the source in the connection, true = yes.
|
|
||||||
*/
|
*/
|
||||||
export function GoalConnects(_thisNode: Node, _otherNode: Node, _isThisSource: boolean) {
|
export function GoalConnectionTarget(_thisNode: Node, _sourceNodeId: string) {
|
||||||
// Replace this for connection logic
|
// no additional connection logic exists yet
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This function is called whenever a connection is made with this node type as the source
|
||||||
|
* @param _thisNode the node of this node type which function is called
|
||||||
|
* @param _targetNodeId the target of the created connection
|
||||||
|
*/
|
||||||
|
export function GoalConnectionSource(_thisNode: Node, _targetNodeId: string) {
|
||||||
|
// no additional connection logic exists yet
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This function is called whenever a connection is disconnected with this node type as the target
|
||||||
|
* @param _thisNode the node of this node type which function is called
|
||||||
|
* @param _sourceNodeId the source of the disconnected connection
|
||||||
|
*/
|
||||||
|
export function GoalDisconnectionTarget(_thisNode: Node, _sourceNodeId: string) {
|
||||||
|
// no additional connection logic exists yet
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This function is called whenever a connection is disconnected with this node type as the source
|
||||||
|
* @param _thisNode the node of this node type which function is called
|
||||||
|
* @param _targetNodeId the target of the diconnected connection
|
||||||
|
*/
|
||||||
|
export function GoalDisconnectionSource(_thisNode: Node, _targetNodeId: string) {
|
||||||
|
// no additional connection logic exists yet
|
||||||
}
|
}
|
||||||
@@ -8,4 +8,5 @@ export const NormNodeDefaults: NormNodeData = {
|
|||||||
droppable: true,
|
droppable: true,
|
||||||
norm: "",
|
norm: "",
|
||||||
hasReduce: true,
|
hasReduce: true,
|
||||||
|
critical: false,
|
||||||
};
|
};
|
||||||
@@ -21,6 +21,7 @@ export type NormNodeData = {
|
|||||||
droppable: boolean;
|
droppable: boolean;
|
||||||
norm: string;
|
norm: string;
|
||||||
hasReduce: boolean;
|
hasReduce: boolean;
|
||||||
|
critical: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type NormNode = Node<NormNodeData>
|
export type NormNode = Node<NormNodeData>
|
||||||
@@ -35,11 +36,16 @@ export default function NormNode(props: NodeProps<NormNode>) {
|
|||||||
const {updateNodeData} = useFlowStore();
|
const {updateNodeData} = useFlowStore();
|
||||||
|
|
||||||
const text_input_id = `norm_${props.id}_text_input`;
|
const text_input_id = `norm_${props.id}_text_input`;
|
||||||
|
const checkbox_id = `goal_${props.id}_checkbox`;
|
||||||
|
|
||||||
const setValue = (value: string) => {
|
const setValue = (value: string) => {
|
||||||
updateNodeData(props.id, {norm: value});
|
updateNodeData(props.id, {norm: value});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const setCritical = (value: boolean) => {
|
||||||
|
updateNodeData(props.id, {...data, critical: value});
|
||||||
|
}
|
||||||
|
|
||||||
return <>
|
return <>
|
||||||
<Toolbar nodeId={props.id} allowDelete={true}/>
|
<Toolbar nodeId={props.id} allowDelete={true}/>
|
||||||
<div className={`${styles.defaultNode} ${styles.nodeNorm}`}>
|
<div className={`${styles.defaultNode} ${styles.nodeNorm}`}>
|
||||||
@@ -52,6 +58,15 @@ export default function NormNode(props: NodeProps<NormNode>) {
|
|||||||
placeholder={"Pepper should ..."}
|
placeholder={"Pepper should ..."}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
<div className={"flex-row gap-md align-center"}>
|
||||||
|
<label htmlFor={checkbox_id}>Critical:</label>
|
||||||
|
<input
|
||||||
|
id={checkbox_id}
|
||||||
|
type={"checkbox"}
|
||||||
|
checked={data.critical || false}
|
||||||
|
onChange={(e) => setCritical(e.target.checked)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
<Handle type="source" position={Position.Right} id="norms"/>
|
<Handle type="source" position={Position.Right} id="norms"/>
|
||||||
</div>
|
</div>
|
||||||
</>;
|
</>;
|
||||||
@@ -60,8 +75,8 @@ export default function NormNode(props: NodeProps<NormNode>) {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Reduces each Norm, including its children down into its relevant data.
|
* Reduces each Norm, including its children down into its relevant data.
|
||||||
* @param node: The Node Properties of this node.
|
* @param node The Node Properties of this node.
|
||||||
* @param _nodes: all the nodes in the graph
|
* @param _nodes all the nodes in the graph
|
||||||
*/
|
*/
|
||||||
export function NormReduce(node: Node, _nodes: Node[]) {
|
export function NormReduce(node: Node, _nodes: Node[]) {
|
||||||
const data = node.data as NormNodeData;
|
const data = node.data as NormNodeData;
|
||||||
@@ -69,14 +84,42 @@ export function NormReduce(node: Node, _nodes: Node[]) {
|
|||||||
id: node.id,
|
id: node.id,
|
||||||
label: data.label,
|
label: data.label,
|
||||||
norm: data.norm,
|
norm: data.norm,
|
||||||
|
critical: data.critical,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This function is called whenever a connection is made with this node type (Norm)
|
* This function is called whenever a connection is made with this node type as the target
|
||||||
* @param _thisNode the node of this node type which function is called
|
* @param _thisNode the node of this node type which function is called
|
||||||
* @param _otherNode the other node which was part of the connection
|
* @param _sourceNodeId the source of the received connection
|
||||||
* @param _isThisSource whether this instance of the node was the source in the connection, true = yes.
|
|
||||||
*/
|
*/
|
||||||
export function NormConnects(_thisNode: Node, _otherNode: Node, _isThisSource: boolean) {
|
export function NormConnectionTarget(_thisNode: Node, _sourceNodeId: string) {
|
||||||
|
// no additional connection logic exists yet
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This function is called whenever a connection is made with this node type as the source
|
||||||
|
* @param _thisNode the node of this node type which function is called
|
||||||
|
* @param _targetNodeId the target of the created connection
|
||||||
|
*/
|
||||||
|
export function NormConnectionSource(_thisNode: Node, _targetNodeId: string) {
|
||||||
|
// no additional connection logic exists yet
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This function is called whenever a connection is disconnected with this node type as the target
|
||||||
|
* @param _thisNode the node of this node type which function is called
|
||||||
|
* @param _sourceNodeId the source of the disconnected connection
|
||||||
|
*/
|
||||||
|
export function NormDisconnectionTarget(_thisNode: Node, _sourceNodeId: string) {
|
||||||
|
// no additional connection logic exists yet
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This function is called whenever a connection is disconnected with this node type as the source
|
||||||
|
* @param _thisNode the node of this node type which function is called
|
||||||
|
* @param _targetNodeId the target of the diconnected connection
|
||||||
|
*/
|
||||||
|
export function NormDisconnectionSource(_thisNode: Node, _targetNodeId: string) {
|
||||||
|
// no additional connection logic exists yet
|
||||||
}
|
}
|
||||||
@@ -2,11 +2,11 @@ import {
|
|||||||
Handle,
|
Handle,
|
||||||
type NodeProps,
|
type NodeProps,
|
||||||
Position,
|
Position,
|
||||||
type Node,
|
type Node
|
||||||
} from '@xyflow/react';
|
} from '@xyflow/react';
|
||||||
import { Toolbar } from '../components/NodeComponents';
|
import { Toolbar } from '../components/NodeComponents';
|
||||||
import styles from '../../VisProg.module.css';
|
import styles from '../../VisProg.module.css';
|
||||||
import { NodeReduces, NodesInPhase, NodeTypes } from '../NodeRegistry';
|
import { NodeReduces, NodesInPhase, NodeTypes} from '../NodeRegistry';
|
||||||
import useFlowStore from '../VisProgStores';
|
import useFlowStore from '../VisProgStores';
|
||||||
import { TextField } from '../../../../components/TextField';
|
import { TextField } from '../../../../components/TextField';
|
||||||
|
|
||||||
@@ -104,15 +104,45 @@ export function PhaseReduce(node: Node, nodes: Node[]) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This function is called whenever a connection is made with this node type (phase)
|
* This function is called whenever a connection is made with this node type as the target (phase)
|
||||||
* @param thisNode the node of this node type which function is called
|
* @param _thisNode the node of this node type which function is called
|
||||||
* @param otherNode the other node which was part of the connection
|
* @param _sourceNodeId the source of the received connection
|
||||||
* @param isThisSource whether this instance of the node was the source in the connection, true = yes.
|
|
||||||
*/
|
*/
|
||||||
export function PhaseConnects(thisNode: Node, otherNode: Node, isThisSource: boolean) {
|
export function PhaseConnectionTarget(_thisNode: Node, _sourceNodeId: string) {
|
||||||
console.log("Connect functionality called.")
|
const node = _thisNode as PhaseNode
|
||||||
const node = thisNode as PhaseNode
|
|
||||||
const data = node.data as PhaseNodeData
|
const data = node.data as PhaseNodeData
|
||||||
if (!isThisSource)
|
// we only add none phase nodes to the children
|
||||||
data.children.push(otherNode.id)
|
if (!(useFlowStore.getState().nodes.find((node) => node.id === _sourceNodeId && node.type === 'phase'))) {
|
||||||
|
data.children.push(_sourceNodeId)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This function is called whenever a connection is made with this node type as the source (phase)
|
||||||
|
* @param _thisNode the node of this node type which function is called
|
||||||
|
* @param _targetNodeId the target of the created connection
|
||||||
|
*/
|
||||||
|
export function PhaseConnectionSource(_thisNode: Node, _targetNodeId: string) {
|
||||||
|
// no additional connection logic exists yet
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This function is called whenever a connection is disconnected with this node type as the target (phase)
|
||||||
|
* @param _thisNode the node of this node type which function is called
|
||||||
|
* @param _sourceNodeId the source of the disconnected connection
|
||||||
|
*/
|
||||||
|
export function PhaseDisconnectionTarget(_thisNode: Node, _sourceNodeId: string) {
|
||||||
|
const node = _thisNode as PhaseNode
|
||||||
|
const data = node.data as PhaseNodeData
|
||||||
|
data.children = data.children.filter((child) => { if (child != _sourceNodeId) return child; });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This function is called whenever a connection is disconnected with this node type as the source (phase)
|
||||||
|
* @param _thisNode the node of this node type which function is called
|
||||||
|
* @param _targetNodeId the target of the diconnected connection
|
||||||
|
*/
|
||||||
|
export function PhaseDisconnectionSource(_thisNode: Node, _targetNodeId: string) {
|
||||||
|
// no additional connection logic exists yet
|
||||||
}
|
}
|
||||||
@@ -51,10 +51,37 @@ export function StartReduce(node: Node, _nodes: Node[]) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This function is called whenever a connection is made with this node type (start)
|
* This function is called whenever a connection is made with this node type as the target
|
||||||
* @param _thisNode the node of this node type which function is called
|
* @param _thisNode the node of this node type which function is called
|
||||||
* @param _otherNode the other node which was part of the connection
|
* @param _sourceNodeId the source of the received connection
|
||||||
* @param _isThisSource whether this instance of the node was the source in the connection, true = yes.
|
|
||||||
*/
|
*/
|
||||||
export function StartConnects(_thisNode: Node, _otherNode: Node, _isThisSource: boolean) {
|
export function StartConnectionTarget(_thisNode: Node, _sourceNodeId: string) {
|
||||||
|
// no additional connection logic exists yet
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This function is called whenever a connection is made with this node type as the source
|
||||||
|
* @param _thisNode the node of this node type which function is called
|
||||||
|
* @param _targetNodeId the target of the created connection
|
||||||
|
*/
|
||||||
|
export function StartConnectionSource(_thisNode: Node, _targetNodeId: string) {
|
||||||
|
// no additional connection logic exists yet
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This function is called whenever a connection is disconnected with this node type as the target
|
||||||
|
* @param _thisNode the node of this node type which function is called
|
||||||
|
* @param _sourceNodeId the source of the disconnected connection
|
||||||
|
*/
|
||||||
|
export function StartDisconnectionTarget(_thisNode: Node, _sourceNodeId: string) {
|
||||||
|
// no additional connection logic exists yet
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This function is called whenever a connection is disconnected with this node type as the source
|
||||||
|
* @param _thisNode the node of this node type which function is called
|
||||||
|
* @param _targetNodeId the target of the diconnected connection
|
||||||
|
*/
|
||||||
|
export function StartDisconnectionSource(_thisNode: Node, _targetNodeId: string) {
|
||||||
|
// no additional connection logic exists yet
|
||||||
}
|
}
|
||||||
@@ -102,13 +102,39 @@ export function TriggerReduce(node: Node, _nodes: Node[]) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This function is called whenever a connection is made with this node type (trigger)
|
* This function is called whenever a connection is made with this node type as the target
|
||||||
* @param _thisNode the node of this node type which function is called
|
* @param _thisNode the node of this node type which function is called
|
||||||
* @param _otherNode the other node which was part of the connection
|
* @param _sourceNodeId the source of the received connection
|
||||||
* @param _isThisSource whether this instance of the node was the source in the connection, true = yes.
|
|
||||||
*/
|
*/
|
||||||
export function TriggerConnects(_thisNode: Node, _otherNode: Node, _isThisSource: boolean) {
|
export function TriggerConnectionTarget(_thisNode: Node, _sourceNodeId: string) {
|
||||||
|
// no additional connection logic exists yet
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This function is called whenever a connection is made with this node type as the source
|
||||||
|
* @param _thisNode the node of this node type which function is called
|
||||||
|
* @param _targetNodeId the target of the created connection
|
||||||
|
*/
|
||||||
|
export function TriggerConnectionSource(_thisNode: Node, _targetNodeId: string) {
|
||||||
|
// no additional connection logic exists yet
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This function is called whenever a connection is disconnected with this node type as the target
|
||||||
|
* @param _thisNode the node of this node type which function is called
|
||||||
|
* @param _sourceNodeId the source of the disconnected connection
|
||||||
|
*/
|
||||||
|
export function TriggerDisconnectionTarget(_thisNode: Node, _sourceNodeId: string) {
|
||||||
|
// no additional connection logic exists yet
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This function is called whenever a connection is disconnected with this node type as the source
|
||||||
|
* @param _thisNode the node of this node type which function is called
|
||||||
|
* @param _targetNodeId the target of the diconnected connection
|
||||||
|
*/
|
||||||
|
export function TriggerDisconnectionSource(_thisNode: Node, _targetNodeId: string) {
|
||||||
|
// no additional connection logic exists yet
|
||||||
}
|
}
|
||||||
|
|
||||||
// Definitions for the possible triggers, being keywords and emotions
|
// Definitions for the possible triggers, being keywords and emotions
|
||||||
|
|||||||
19
src/utils/SaveLoad.ts
Normal file
19
src/utils/SaveLoad.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import {type Edge, type Node } from "@xyflow/react";
|
||||||
|
|
||||||
|
export type SavedProject = {
|
||||||
|
name: string;
|
||||||
|
savedASavedProject: string; // ISO timestamp
|
||||||
|
nodes: Node[];
|
||||||
|
edges: Edge[];
|
||||||
|
};
|
||||||
|
|
||||||
|
// Creates a JSON Blob containing the current visual program (nodes + edges)
|
||||||
|
export function makeProjectBlob(name: string, nodes: Node[], edges: Edge[]): Blob {
|
||||||
|
const payload = {
|
||||||
|
name,
|
||||||
|
savedAt: new Date().toISOString(),
|
||||||
|
nodes,
|
||||||
|
edges,
|
||||||
|
};
|
||||||
|
return new Blob([JSON.stringify(payload, null, 2)], { type: "application/json" });
|
||||||
|
}
|
||||||
81
src/utils/programStore.ts
Normal file
81
src/utils/programStore.ts
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
import {create} from "zustand";
|
||||||
|
|
||||||
|
// the type of a reduced program
|
||||||
|
export type ReducedProgram = { phases: Record<string, unknown>[] };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* the type definition of the programStore
|
||||||
|
*/
|
||||||
|
export type ProgramState = {
|
||||||
|
// Basic store functionality:
|
||||||
|
currentProgram: ReducedProgram;
|
||||||
|
setProgramState: (state: ReducedProgram) => void;
|
||||||
|
getProgramState: () => ReducedProgram;
|
||||||
|
|
||||||
|
// Utility functions:
|
||||||
|
// to avoid having to manually go through the entire state for every instance where data is required
|
||||||
|
getPhaseIds: () => string[];
|
||||||
|
getNormsInPhase: (currentPhaseId: string) => Record<string, unknown>[];
|
||||||
|
getGoalsInPhase: (currentPhaseId: string) => Record<string, unknown>[];
|
||||||
|
getTriggersInPhase: (currentPhaseId: string) => Record<string, unknown>[];
|
||||||
|
// if more specific utility functions are needed they can be added here:
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* the ProgramStore can be used to access all information of the most recently sent program,
|
||||||
|
* it contains basic functions to set and get the current program.
|
||||||
|
* And it contains some utility functions that allow you to easily gain access
|
||||||
|
* to the norms, triggers and goals of a specific phase.
|
||||||
|
*/
|
||||||
|
const useProgramStore = create<ProgramState>((set, get) => ({
|
||||||
|
currentProgram: { phases: [] as Record<string, unknown>[]},
|
||||||
|
/**
|
||||||
|
* sets the current program by cloning the provided program using a structuredClone
|
||||||
|
*/
|
||||||
|
setProgramState: (program: ReducedProgram) => set({currentProgram: structuredClone(program)}),
|
||||||
|
/**
|
||||||
|
* gets the current program
|
||||||
|
*/
|
||||||
|
getProgramState: () => get().currentProgram,
|
||||||
|
|
||||||
|
// utility functions:
|
||||||
|
/**
|
||||||
|
* gets the ids of all phases in the program
|
||||||
|
*/
|
||||||
|
getPhaseIds: () => get().currentProgram.phases.map(entry => entry["id"] as string),
|
||||||
|
/**
|
||||||
|
* gets the norms for the provided phase
|
||||||
|
*/
|
||||||
|
getNormsInPhase: (currentPhaseId) => {
|
||||||
|
const program = get().currentProgram;
|
||||||
|
const phase = program.phases.find(val => val["id"] === currentPhaseId);
|
||||||
|
if (phase) {
|
||||||
|
return phase["norms"] as Record<string, unknown>[];
|
||||||
|
}
|
||||||
|
throw new Error(`phase with id:"${currentPhaseId}" not found`)
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* gets the goals for the provided phase
|
||||||
|
*/
|
||||||
|
getGoalsInPhase: (currentPhaseId) => {
|
||||||
|
const program = get().currentProgram;
|
||||||
|
const phase = program.phases.find(val => val["id"] === currentPhaseId);
|
||||||
|
if (phase) {
|
||||||
|
return phase["goals"] as Record<string, unknown>[];
|
||||||
|
}
|
||||||
|
throw new Error(`phase with id:"${currentPhaseId}" not found`)
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* gets the triggers for the provided phase
|
||||||
|
*/
|
||||||
|
getTriggersInPhase: (currentPhaseId) => {
|
||||||
|
const program = get().currentProgram;
|
||||||
|
const phase = program.phases.find(val => val["id"] === currentPhaseId);
|
||||||
|
if (phase) {
|
||||||
|
return phase["triggers"] as Record<string, unknown>[];
|
||||||
|
}
|
||||||
|
throw new Error(`phase with id:"${currentPhaseId}" not found`)
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
export default useProgramStore;
|
||||||
83
test/pages/simpleProgram/SimpleProgram.tsx
Normal file
83
test/pages/simpleProgram/SimpleProgram.tsx
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
import { render, screen, fireEvent } from "@testing-library/react";
|
||||||
|
import SimpleProgram from "../../../src/pages/SimpleProgram/SimpleProgram";
|
||||||
|
import useProgramStore from "../../../src/utils/programStore";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper to preload the program store before rendering.
|
||||||
|
*/
|
||||||
|
function loadProgram(phases: Record<string, unknown>[]) {
|
||||||
|
useProgramStore.getState().setProgramState({ phases });
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("SimpleProgram", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
loadProgram([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("shows empty state when no program is loaded", () => {
|
||||||
|
render(<SimpleProgram />);
|
||||||
|
expect(screen.getByText("No program loaded.")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("renders first phase content", () => {
|
||||||
|
loadProgram([
|
||||||
|
{
|
||||||
|
id: "phase-1",
|
||||||
|
norms: [{ id: "n1", norm: "Be polite" }],
|
||||||
|
goals: [{ id: "g1", description: "Finish task", achieved: true }],
|
||||||
|
triggers: [{ id: "t1", label: "Keyword trigger" }],
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
render(<SimpleProgram />);
|
||||||
|
|
||||||
|
expect(screen.getByText("Phase 1 / 1")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("Be polite")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("Finish task")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("Keyword trigger")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("allows navigating between phases", () => {
|
||||||
|
loadProgram([
|
||||||
|
{
|
||||||
|
id: "phase-1",
|
||||||
|
norms: [],
|
||||||
|
goals: [],
|
||||||
|
triggers: [],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "phase-2",
|
||||||
|
norms: [{ id: "n2", norm: "Be careful" }],
|
||||||
|
goals: [],
|
||||||
|
triggers: [],
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
render(<SimpleProgram />);
|
||||||
|
|
||||||
|
expect(screen.getByText("Phase 1 / 2")).toBeInTheDocument();
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByText("Next ▶"));
|
||||||
|
|
||||||
|
expect(screen.getByText("Phase 2 / 2")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("Be careful")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("prev button is disabled on first phase", () => {
|
||||||
|
loadProgram([
|
||||||
|
{ id: "phase-1", norms: [], goals: [], triggers: [] },
|
||||||
|
]);
|
||||||
|
|
||||||
|
render(<SimpleProgram />);
|
||||||
|
expect(screen.getByText("◀ Prev")).toBeDisabled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("next button is disabled on last phase", () => {
|
||||||
|
loadProgram([
|
||||||
|
{ id: "phase-1", norms: [], goals: [], triggers: [] },
|
||||||
|
]);
|
||||||
|
|
||||||
|
render(<SimpleProgram />);
|
||||||
|
expect(screen.getByText("Next ▶")).toBeDisabled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,4 +1,7 @@
|
|||||||
import {act} from '@testing-library/react';
|
import {act} from '@testing-library/react';
|
||||||
|
import type {Connection, Edge, Node} from "@xyflow/react";
|
||||||
|
import { NodeDisconnections } from "../../../../src/pages/VisProgPage/visualProgrammingUI/NodeRegistry.ts";
|
||||||
|
import type {PhaseNodeData} from "../../../../src/pages/VisProgPage/visualProgrammingUI/nodes/PhaseNode.tsx";
|
||||||
import useFlowStore from '../../../../src/pages/VisProgPage/visualProgrammingUI/VisProgStores.tsx';
|
import useFlowStore from '../../../../src/pages/VisProgPage/visualProgrammingUI/VisProgStores.tsx';
|
||||||
import { mockReactFlow } from '../../../setupFlowTests.ts';
|
import { mockReactFlow } from '../../../setupFlowTests.ts';
|
||||||
|
|
||||||
@@ -6,18 +9,187 @@ beforeAll(() => {
|
|||||||
mockReactFlow();
|
mockReactFlow();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// default state values for testing,
|
||||||
|
const normNode: Node = {
|
||||||
|
id: 'norm-1',
|
||||||
|
type: 'norm',
|
||||||
|
position: { x: 0, y: 0 },
|
||||||
|
data: {
|
||||||
|
label: 'Test Norm',
|
||||||
|
droppable: true,
|
||||||
|
norm: 'Test',
|
||||||
|
hasReduce: true,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const phaseNode: Node = {
|
||||||
|
id: 'phase-1',
|
||||||
|
type: 'phase',
|
||||||
|
position: { x: 100, y: 0 },
|
||||||
|
data: {
|
||||||
|
label: 'Phase 1',
|
||||||
|
droppable: true,
|
||||||
|
children: ["norm-1"],
|
||||||
|
hasReduce: true,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const testEdge: Edge = {
|
||||||
|
id: 'xy-edge__1-2',
|
||||||
|
source: 'norm-1',
|
||||||
|
target: 'phase-1',
|
||||||
|
sourceHandle: null,
|
||||||
|
targetHandle: null,
|
||||||
|
}
|
||||||
|
|
||||||
|
const testStateReconnectEnd = {
|
||||||
|
nodes: [phaseNode, normNode],
|
||||||
|
edges: [testEdge],
|
||||||
|
}
|
||||||
|
|
||||||
|
const phaseNodeUnconnected = {
|
||||||
|
id: 'phase-2',
|
||||||
|
type: 'phase',
|
||||||
|
position: { x: 100, y: 0 },
|
||||||
|
data: {
|
||||||
|
label: 'Phase 2',
|
||||||
|
droppable: true,
|
||||||
|
children: [],
|
||||||
|
hasReduce: true,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const testConnection: Connection = {
|
||||||
|
source: 'norm-1',
|
||||||
|
target: 'phase-2',
|
||||||
|
sourceHandle: null,
|
||||||
|
targetHandle: null,
|
||||||
|
}
|
||||||
|
const testStateOnConnect = {
|
||||||
|
nodes: [phaseNodeUnconnected, normNode],
|
||||||
|
edges: [],
|
||||||
|
}
|
||||||
|
|
||||||
describe('FlowStore Functionality', () => {
|
describe('FlowStore Functionality', () => {
|
||||||
describe('Node changes', () => {
|
describe('Node changes', () => {
|
||||||
// currently just using a single function from the ReactFlow library,
|
// currently just using a single function from the ReactFlow library,
|
||||||
// so testing would mean we are testing already tested behavior.
|
// so testing would mean we are testing already tested behavior.
|
||||||
// if implementation gets modified tests should be added for custom behavior
|
// if implementation gets modified tests should be added for custom behavior
|
||||||
});
|
});
|
||||||
|
describe('ReactFlow onEdgesDelete', () => {
|
||||||
|
test('Deleted edge is reflected in removed phaseNode child', () => {
|
||||||
|
const {onEdgesDelete} = useFlowStore.getState();
|
||||||
|
|
||||||
|
useFlowStore.setState({
|
||||||
|
nodes: [{
|
||||||
|
id: 'phase-1',
|
||||||
|
type: 'phase',
|
||||||
|
position: { x: 100, y: 0 },
|
||||||
|
data: {
|
||||||
|
label: 'Phase 1',
|
||||||
|
droppable: true,
|
||||||
|
children: ["norm-1"],
|
||||||
|
hasReduce: true,
|
||||||
|
},
|
||||||
|
},{
|
||||||
|
id: 'norm-1',
|
||||||
|
type: 'norm',
|
||||||
|
position: { x: 0, y: 0 },
|
||||||
|
data: {
|
||||||
|
label: 'Test Norm',
|
||||||
|
droppable: true,
|
||||||
|
norm: 'Test',
|
||||||
|
hasReduce: true,
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
edges: [], // edges is empty as onEdgesDelete is triggered after the edges are deleted
|
||||||
|
})
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
onEdgesDelete([testEdge])
|
||||||
|
});
|
||||||
|
|
||||||
|
const outcome = useFlowStore.getState();
|
||||||
|
expect((outcome.nodes[0].data as PhaseNodeData).children.length).toBe(0);
|
||||||
|
})
|
||||||
|
test('Deleted edge is reflected in phaseNode,even if normNode was already deleted and caused edge removal', () => {
|
||||||
|
const { onEdgesDelete } = useFlowStore.getState();
|
||||||
|
useFlowStore.setState({
|
||||||
|
nodes: [{
|
||||||
|
id: 'phase-1',
|
||||||
|
type: 'phase',
|
||||||
|
position: { x: 100, y: 0 },
|
||||||
|
data: {
|
||||||
|
label: 'Phase 1',
|
||||||
|
droppable: true,
|
||||||
|
children: ["norm-1"],
|
||||||
|
hasReduce: true,
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
edges: [], // edges is empty as onEdgesDelete is triggered after the edges are deleted
|
||||||
|
})
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
onEdgesDelete([testEdge]);
|
||||||
|
})
|
||||||
|
|
||||||
|
const outcome = useFlowStore.getState();
|
||||||
|
expect((outcome.nodes[0].data as PhaseNodeData).children.length).toBe(0);
|
||||||
|
})
|
||||||
|
test('edge removal resulting from deletion of targetNode calls only the connection function for the sourceNode', () => {
|
||||||
|
const { onEdgesDelete } = useFlowStore.getState();
|
||||||
|
useFlowStore.setState({
|
||||||
|
nodes: [{
|
||||||
|
id: 'norm-1',
|
||||||
|
type: 'norm',
|
||||||
|
position: { x: 0, y: 0 },
|
||||||
|
data: {
|
||||||
|
label: 'Test Norm',
|
||||||
|
droppable: true,
|
||||||
|
norm: 'Test',
|
||||||
|
hasReduce: true,
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
edges: [], // edges is empty as onEdgesDelete is triggered after the edges are deleted
|
||||||
|
})
|
||||||
|
|
||||||
|
const targetDisconnectSpy = jest.spyOn(NodeDisconnections.Targets, 'phase');
|
||||||
|
const sourceDisconnectSpy = jest.spyOn(NodeDisconnections.Sources, 'norm');
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
onEdgesDelete([testEdge]);
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(sourceDisconnectSpy).toHaveBeenCalledWith(normNode, 'phase-1');
|
||||||
|
expect(targetDisconnectSpy).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
sourceDisconnectSpy.mockRestore();
|
||||||
|
targetDisconnectSpy.mockRestore();
|
||||||
|
})
|
||||||
|
})
|
||||||
describe('Edge changes', () => {
|
describe('Edge changes', () => {
|
||||||
// currently just using a single function from the ReactFlow library,
|
// currently just using a single function from the ReactFlow library,
|
||||||
// so testing would mean we are testing already tested behavior.
|
// so testing would mean we are testing already tested behavior.
|
||||||
// if implementation gets modified tests should be added for custom behavior
|
// if implementation gets modified tests should be added for custom behavior
|
||||||
})
|
})
|
||||||
describe('ReactFlow onConnect', () => {
|
describe('ReactFlow onConnect', () => {
|
||||||
|
test('Adds connecting node to children of phaseNode', () => {
|
||||||
|
const {onConnect} = useFlowStore.getState();
|
||||||
|
useFlowStore.setState({
|
||||||
|
nodes: testStateOnConnect.nodes,
|
||||||
|
edges: testStateOnConnect.edges
|
||||||
|
})
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
onConnect(testConnection);
|
||||||
|
})
|
||||||
|
|
||||||
|
const outcome = useFlowStore.getState();
|
||||||
|
|
||||||
|
// phaseNode adds the normNode to its children
|
||||||
|
expect((outcome.nodes[0].data as PhaseNodeData).children).toEqual(['norm-1']);
|
||||||
|
|
||||||
|
})
|
||||||
test('adds an edge when onConnect is triggered', () => {
|
test('adds an edge when onConnect is triggered', () => {
|
||||||
const {onConnect} = useFlowStore.getState();
|
const {onConnect} = useFlowStore.getState();
|
||||||
|
|
||||||
@@ -39,6 +211,53 @@ describe('FlowStore Functionality', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
describe('ReactFlow onReconnect', () => {
|
describe('ReactFlow onReconnect', () => {
|
||||||
|
test('PhaseNodes correctly change their children', () => {
|
||||||
|
const {onReconnect} = useFlowStore.getState();
|
||||||
|
useFlowStore.setState({
|
||||||
|
nodes: [{
|
||||||
|
id: 'phase-1',
|
||||||
|
type: 'phase',
|
||||||
|
position: { x: 100, y: 0 },
|
||||||
|
data: {
|
||||||
|
label: 'Phase 1',
|
||||||
|
droppable: true,
|
||||||
|
children: ["norm-1"],
|
||||||
|
hasReduce: true,
|
||||||
|
},
|
||||||
|
},{
|
||||||
|
id: 'phase-2',
|
||||||
|
type: 'phase',
|
||||||
|
position: { x: 100, y: 0 },
|
||||||
|
data: {
|
||||||
|
label: 'Phase 2',
|
||||||
|
droppable: true,
|
||||||
|
children: [],
|
||||||
|
hasReduce: true,
|
||||||
|
},
|
||||||
|
},{
|
||||||
|
id: 'norm-1',
|
||||||
|
type: 'norm',
|
||||||
|
position: { x: 0, y: 0 },
|
||||||
|
data: {
|
||||||
|
label: 'Test Norm',
|
||||||
|
droppable: true,
|
||||||
|
norm: 'Test',
|
||||||
|
hasReduce: true,
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
edges: [testEdge],
|
||||||
|
})
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
onReconnect(testEdge, testConnection);
|
||||||
|
})
|
||||||
|
|
||||||
|
const outcome = useFlowStore.getState();
|
||||||
|
|
||||||
|
// phaseNodes lose and gain children when norm node's connection is changed from phaseNode to PhaseNodeUnconnected
|
||||||
|
expect((outcome.nodes[1].data as PhaseNodeData).children).toEqual(['norm-1']);
|
||||||
|
expect((outcome.nodes[0].data as PhaseNodeData).children).toEqual([]);
|
||||||
|
})
|
||||||
test('reconnects an existing edge when onReconnect is triggered', () => {
|
test('reconnects an existing edge when onReconnect is triggered', () => {
|
||||||
const {onReconnect} = useFlowStore.getState();
|
const {onReconnect} = useFlowStore.getState();
|
||||||
const oldEdge = {
|
const oldEdge = {
|
||||||
@@ -93,36 +312,63 @@ describe('FlowStore Functionality', () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
test('successfully removes edge if no successful reconnect occurred', () => {
|
test('successfully removes edge if no successful reconnect occurred', () => {
|
||||||
const {onReconnectEnd} = useFlowStore.getState();
|
const {onReconnectEnd} = useFlowStore.getState();
|
||||||
useFlowStore.setState({edgeReconnectSuccessful: false});
|
useFlowStore.setState({
|
||||||
|
edgeReconnectSuccessful: false,
|
||||||
|
edges: testStateReconnectEnd.edges,
|
||||||
|
nodes: testStateReconnectEnd.nodes
|
||||||
|
});
|
||||||
|
|
||||||
act(() => {
|
act(() => {
|
||||||
onReconnectEnd(null, {id: 'xy-edge__A-B'});
|
onReconnectEnd(null, testEdge);
|
||||||
});
|
});
|
||||||
|
|
||||||
const updatedState = useFlowStore.getState();
|
const updatedState = useFlowStore.getState();
|
||||||
expect(updatedState.edgeReconnectSuccessful).toBe(true);
|
expect(updatedState.edgeReconnectSuccessful).toBe(true);
|
||||||
expect(updatedState.edges).toHaveLength(0);
|
expect(updatedState.edges).toHaveLength(0);
|
||||||
|
expect(updatedState.nodes[0].data.children).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('does not remove reconnecting edge if successful reconnect occurred', () => {
|
test('does not remove reconnecting edge if successful reconnect occurred', () => {
|
||||||
const {onReconnectEnd} = useFlowStore.getState();
|
const {onReconnectEnd} = useFlowStore.getState();
|
||||||
|
useFlowStore.setState({
|
||||||
|
edgeReconnectSuccessful: true,
|
||||||
|
edges: [testEdge],
|
||||||
|
nodes: [{
|
||||||
|
id: 'phase-1',
|
||||||
|
type: 'phase',
|
||||||
|
position: { x: 100, y: 0 },
|
||||||
|
data: {
|
||||||
|
label: 'Phase 1',
|
||||||
|
droppable: true,
|
||||||
|
children: ["norm-1"],
|
||||||
|
hasReduce: true,
|
||||||
|
},
|
||||||
|
},{
|
||||||
|
id: 'norm-1',
|
||||||
|
type: 'norm',
|
||||||
|
position: { x: 0, y: 0 },
|
||||||
|
data: {
|
||||||
|
label: 'Test Norm',
|
||||||
|
droppable: true,
|
||||||
|
norm: 'Test',
|
||||||
|
hasReduce: true,
|
||||||
|
},
|
||||||
|
}]
|
||||||
|
});
|
||||||
|
|
||||||
act(() => {
|
act(() => {
|
||||||
onReconnectEnd(null, {id: 'xy-edge__A-B'});
|
onReconnectEnd(null, testEdge);
|
||||||
});
|
});
|
||||||
|
|
||||||
const updatedState = useFlowStore.getState();
|
const updatedState = useFlowStore.getState();
|
||||||
expect(updatedState.edgeReconnectSuccessful).toBe(true);
|
expect(updatedState.edgeReconnectSuccessful).toBe(true);
|
||||||
expect(updatedState.edges).toHaveLength(1);
|
expect(updatedState.edges).toHaveLength(1);
|
||||||
expect(updatedState.edges).toMatchObject([
|
expect(updatedState.edges).toMatchObject([testEdge]);
|
||||||
{
|
expect(updatedState.nodes[0].data.children).toEqual(["norm-1"]);
|
||||||
id: 'xy-edge__A-B',
|
|
||||||
source: 'A',
|
|
||||||
target: 'B'
|
|
||||||
}]
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
describe('ReactFlow deleteNode', () => {
|
describe('ReactFlow deleteNode', () => {
|
||||||
|
|||||||
@@ -0,0 +1,154 @@
|
|||||||
|
// SaveLoadPanel.all.test.tsx
|
||||||
|
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||||
|
import useFlowStore from '../../../../../src/pages/VisProgPage/visualProgrammingUI/VisProgStores.tsx';
|
||||||
|
import SaveLoadPanel from '../../../../../src/pages/VisProgPage/visualProgrammingUI/components/SaveLoadPanel.tsx';
|
||||||
|
import { makeProjectBlob } from '../../../../../src/utils/SaveLoad.ts';
|
||||||
|
import { mockReactFlow } from "../../../../setupFlowTests.ts"; // optional helper if present
|
||||||
|
|
||||||
|
// helper to read Blob contents in tests (works in Node/Jest env)
|
||||||
|
async function blobToText(blob: Blob): Promise<string> {
|
||||||
|
if (typeof (blob as any).text === "function") return await (blob as any).text();
|
||||||
|
if (typeof (blob as any).arrayBuffer === "function") {
|
||||||
|
const buf = await (blob as any).arrayBuffer();
|
||||||
|
return new TextDecoder().decode(buf);
|
||||||
|
}
|
||||||
|
return await new Promise<string>((resolve, reject) => {
|
||||||
|
const fr = new FileReader();
|
||||||
|
fr.onload = () => resolve(String(fr.result));
|
||||||
|
fr.onerror = () => reject(fr.error);
|
||||||
|
fr.readAsText(blob);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
// if you have a mockReactFlow helper used in other tests, call it
|
||||||
|
if (typeof mockReactFlow === "function") mockReactFlow();
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
// clear and seed the zustand store to a known empty state
|
||||||
|
act(() => {
|
||||||
|
const { setNodes, setEdges } = useFlowStore.getState();
|
||||||
|
setNodes([]);
|
||||||
|
setEdges([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Ensure URL.createObjectURL exists so jest.spyOn works
|
||||||
|
if (!URL.createObjectURL) URL.createObjectURL = jest.fn();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
jest.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("SaveLoadPanel - combined tests", () => {
|
||||||
|
test("makeProjectBlob creates a valid JSON blob", async () => {
|
||||||
|
const nodes = [
|
||||||
|
{
|
||||||
|
id: "n1",
|
||||||
|
type: "start",
|
||||||
|
position: { x: 0, y: 0 },
|
||||||
|
data: { label: "Start" },
|
||||||
|
} as any,
|
||||||
|
];
|
||||||
|
const edges: any[] = [];
|
||||||
|
|
||||||
|
const blob = makeProjectBlob("my-project", nodes, edges);
|
||||||
|
expect(blob).toBeInstanceOf(Blob);
|
||||||
|
|
||||||
|
const text = await blobToText(blob);
|
||||||
|
const parsed = JSON.parse(text);
|
||||||
|
|
||||||
|
expect(parsed.name).toBe("my-project");
|
||||||
|
expect(typeof parsed.savedAt).toBe("string");
|
||||||
|
expect(Array.isArray(parsed.nodes)).toBe(true);
|
||||||
|
expect(Array.isArray(parsed.edges)).toBe(true);
|
||||||
|
expect(parsed.nodes).toEqual(nodes);
|
||||||
|
expect(parsed.edges).toEqual(edges);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("onSave creates a blob URL and sets anchor href", async () => {
|
||||||
|
// Seed the store so onSave has nodes to save
|
||||||
|
act(() => {
|
||||||
|
useFlowStore.getState().setNodes([
|
||||||
|
{ id: "start", type: "start", position: { x: 0, y: 0 }, data: { label: "start" } } as any,
|
||||||
|
]);
|
||||||
|
useFlowStore.getState().setEdges([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Ensure createObjectURL exists and spy it
|
||||||
|
if (!URL.createObjectURL) URL.createObjectURL = jest.fn();
|
||||||
|
const createObjectURLSpy = jest.spyOn(URL, "createObjectURL").mockReturnValue("blob:fake-url");
|
||||||
|
|
||||||
|
render(<SaveLoadPanel />);
|
||||||
|
|
||||||
|
const saveAnchor = screen.getByText(/Save Graph/i) as HTMLAnchorElement;
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
fireEvent.click(saveAnchor);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(createObjectURLSpy).toHaveBeenCalledTimes(1);
|
||||||
|
const blobArg = createObjectURLSpy.mock.calls[0][0];
|
||||||
|
expect(blobArg).toBeInstanceOf(Blob);
|
||||||
|
|
||||||
|
expect(saveAnchor.getAttribute("href")).toBe("blob:fake-url");
|
||||||
|
|
||||||
|
const text = await blobToText(blobArg as Blob);
|
||||||
|
const parsed = JSON.parse(text);
|
||||||
|
|
||||||
|
expect(parsed.name).toBeDefined();
|
||||||
|
expect(parsed.nodes).toBeDefined();
|
||||||
|
expect(parsed.edges).toBeDefined();
|
||||||
|
|
||||||
|
createObjectURLSpy.mockRestore();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("onLoad with invalid JSON does not update store", async () => {
|
||||||
|
const file = new File(["not json"], "bad.json", { type: "application/json" });
|
||||||
|
file.text = jest.fn(() => Promise.resolve(`{"bad json`));
|
||||||
|
|
||||||
|
window.alert = jest.fn();
|
||||||
|
|
||||||
|
render(<SaveLoadPanel />);
|
||||||
|
const input = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||||
|
expect(input).toBeTruthy();
|
||||||
|
|
||||||
|
// Give some input
|
||||||
|
act(() => {
|
||||||
|
fireEvent.change(input, { target: { files: [file] } });
|
||||||
|
});
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(window.alert).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
const nodesAfter = useFlowStore.getState().nodes;
|
||||||
|
expect(nodesAfter).toHaveLength(0);
|
||||||
|
expect(input.value).toBe("");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("onLoad resolves to null when no file is chosen (user cancels) and does not update store", async () => {
|
||||||
|
render(<SaveLoadPanel />);
|
||||||
|
const input = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||||
|
expect(input).toBeTruthy();
|
||||||
|
|
||||||
|
// Click Load to set resolver
|
||||||
|
const loadButton = screen.getByLabelText(/load graph/i);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
fireEvent.click(loadButton);
|
||||||
|
// simulate user cancelling: change with empty files
|
||||||
|
fireEvent.change(input, { target: { files: [] } });
|
||||||
|
await Promise.resolve();
|
||||||
|
});
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
const nodesAfter = useFlowStore.getState().nodes;
|
||||||
|
const edgesAfter = useFlowStore.getState().edges;
|
||||||
|
expect(nodesAfter).toHaveLength(0);
|
||||||
|
expect(edgesAfter).toHaveLength(0);
|
||||||
|
expect(input.value).toBe("");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,8 +1,12 @@
|
|||||||
import { describe, it, beforeEach } from '@jest/globals';
|
import { describe, it, beforeEach } from '@jest/globals';
|
||||||
import { screen, waitFor } from '@testing-library/react';
|
import { screen, waitFor } from '@testing-library/react';
|
||||||
import userEvent from '@testing-library/user-event';
|
import userEvent from '@testing-library/user-event';
|
||||||
import { renderWithProviders } from '../.././/./../../test-utils/test-utils';
|
import { renderWithProviders } from '../../../../test-utils/test-utils.tsx';
|
||||||
import NormNode, { NormReduce, NormConnects, type NormNodeData } from '../../../../../src/pages/VisProgPage/visualProgrammingUI/nodes/NormNode'
|
import NormNode, {
|
||||||
|
NormReduce,
|
||||||
|
type NormNodeData,
|
||||||
|
NormConnectionSource, NormConnectionTarget
|
||||||
|
} from '../../../../../src/pages/VisProgPage/visualProgrammingUI/nodes/NormNode';
|
||||||
import useFlowStore from '../../../../../src/pages/VisProgPage/visualProgrammingUI/VisProgStores';
|
import useFlowStore from '../../../../../src/pages/VisProgPage/visualProgrammingUI/VisProgStores';
|
||||||
import type { Node } from '@xyflow/react';
|
import type { Node } from '@xyflow/react';
|
||||||
import '@testing-library/jest-dom'
|
import '@testing-library/jest-dom'
|
||||||
@@ -94,6 +98,7 @@ describe('NormNode', () => {
|
|||||||
droppable: true,
|
droppable: true,
|
||||||
norm: '',
|
norm: '',
|
||||||
hasReduce: true,
|
hasReduce: true,
|
||||||
|
critical: false
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -517,7 +522,7 @@ describe('NormNode', () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
expect(() => {
|
expect(() => {
|
||||||
NormConnects(normNode, phaseNode, true);
|
NormConnectionSource(normNode, phaseNode.id);
|
||||||
}).not.toThrow();
|
}).not.toThrow();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -547,7 +552,7 @@ describe('NormNode', () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
expect(() => {
|
expect(() => {
|
||||||
NormConnects(normNode, phaseNode, false);
|
NormConnectionTarget(normNode, phaseNode.id);
|
||||||
}).not.toThrow();
|
}).not.toThrow();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -565,7 +570,8 @@ describe('NormNode', () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
expect(() => {
|
expect(() => {
|
||||||
NormConnects(normNode, normNode, true);
|
NormConnectionTarget(normNode, normNode.id);
|
||||||
|
NormConnectionSource(normNode, normNode.id);
|
||||||
}).not.toThrow();
|
}).not.toThrow();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -622,6 +628,54 @@ describe('NormNode', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('should properly update the store when editing critical checkbox', async () => {
|
||||||
|
const mockNode: Node = {
|
||||||
|
id: 'norm-1',
|
||||||
|
type: 'norm',
|
||||||
|
position: { x: 0, y: 0 },
|
||||||
|
data: {
|
||||||
|
label: 'Test Norm',
|
||||||
|
droppable: true,
|
||||||
|
norm: '',
|
||||||
|
hasReduce: true,
|
||||||
|
critical: false,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
useFlowStore.setState({
|
||||||
|
nodes: [mockNode],
|
||||||
|
edges: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
renderWithProviders(
|
||||||
|
<NormNode
|
||||||
|
id={mockNode.id}
|
||||||
|
type={mockNode.type as string}
|
||||||
|
data={mockNode.data as any}
|
||||||
|
selected={false}
|
||||||
|
isConnectable={true}
|
||||||
|
zIndex={0}
|
||||||
|
dragging={false}
|
||||||
|
selectable={true}
|
||||||
|
deletable={true}
|
||||||
|
draggable={true}
|
||||||
|
positionAbsoluteX={0}
|
||||||
|
positionAbsoluteY={0}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
const checkbox = screen.getByLabelText('Critical:');
|
||||||
|
await user.click(checkbox);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
const state = useFlowStore.getState();
|
||||||
|
expect(state.nodes).toHaveLength(1);
|
||||||
|
expect(state.nodes[0].id).toBe('norm-1');
|
||||||
|
expect(state.nodes[0].data.norm).toBe('');
|
||||||
|
expect(state.nodes[0].data.critical).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
it('should not affect other nodes when updating one norm node', async () => {
|
it('should not affect other nodes when updating one norm node', async () => {
|
||||||
const norm1: Node = {
|
const norm1: Node = {
|
||||||
id: 'norm-1',
|
id: 'norm-1',
|
||||||
|
|||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import useFlowStore from '../../../../../src/pages/VisProgPage/visualProgrammingUI/VisProgStores';
|
||||||
|
import type { PhaseNodeData } from "../../../../../src/pages/VisProgPage/visualProgrammingUI/nodes/PhaseNode";
|
||||||
|
import { getByTestId, render } from '@testing-library/react';
|
||||||
|
import userEvent from '@testing-library/user-event';
|
||||||
|
import VisProgPage from '../../../../../src/pages/VisProgPage/VisProg';
|
||||||
|
|
||||||
|
|
||||||
|
class ResizeObserver {
|
||||||
|
observe() {}
|
||||||
|
unobserve() {}
|
||||||
|
disconnect() {}
|
||||||
|
}
|
||||||
|
window.ResizeObserver = ResizeObserver;
|
||||||
|
|
||||||
|
jest.mock('@neodrag/react', () => ({
|
||||||
|
useDraggable: (ref: React.RefObject<HTMLElement>, options: any) => {
|
||||||
|
// We access the real useEffect from React to attach a listener
|
||||||
|
// This bridges the gap between the test's userEvent and the component's logic
|
||||||
|
const { useEffect } = jest.requireActual('react');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const element = ref.current;
|
||||||
|
if (!element) return;
|
||||||
|
|
||||||
|
// When the test fires a "pointerup" (end of click/drag),
|
||||||
|
// we manually trigger the library's onDragEnd callback.
|
||||||
|
const handlePointerUp = (e: PointerEvent) => {
|
||||||
|
if (options.onDragEnd) {
|
||||||
|
options.onDragEnd({ event: e });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
element.addEventListener('pointerup', handlePointerUp as EventListener);
|
||||||
|
return () => {
|
||||||
|
element.removeEventListener('pointerup', handlePointerUp as EventListener);
|
||||||
|
};
|
||||||
|
}, [ref, options]);
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe('PhaseNode', () => {
|
||||||
|
it('each created phase gets its own children array, not the same reference ', async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
|
||||||
|
const { container } = render(<VisProgPage />);
|
||||||
|
|
||||||
|
// --- Mock ReactFlow bounding box ---
|
||||||
|
// Your DndToolbar checks these values:
|
||||||
|
const flowEl = container.querySelector('.react-flow');
|
||||||
|
jest.spyOn(flowEl!, 'getBoundingClientRect').mockReturnValue({
|
||||||
|
left: 0,
|
||||||
|
right: 800,
|
||||||
|
top: 0,
|
||||||
|
bottom: 600,
|
||||||
|
width: 800,
|
||||||
|
height: 600,
|
||||||
|
x: 0,
|
||||||
|
y: 0,
|
||||||
|
toJSON: () => {},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Find the draggable norm node in the toolbar
|
||||||
|
const phaseButton = getByTestId(container, 'draggable-phase')
|
||||||
|
|
||||||
|
// Simulate dropping phase down in graph (twice)
|
||||||
|
for (let i = 0; i < 2; i++) {
|
||||||
|
await user.pointer([
|
||||||
|
// touch the screen at element1
|
||||||
|
{keys: '[TouchA>]', target: phaseButton},
|
||||||
|
// move the touch pointer to element2
|
||||||
|
{pointerName: 'TouchA', coords: {x: 300, y: 250}},
|
||||||
|
// release the touch pointer at the last position (element2)
|
||||||
|
{keys: '[/TouchA]'},
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find nodes
|
||||||
|
const nodes = useFlowStore.getState().nodes;
|
||||||
|
const p1 = nodes.find((x) => x.id === 'phase-1')!;
|
||||||
|
const p2 = nodes.find((x) => x.id === 'phase-2')!;
|
||||||
|
|
||||||
|
// expect same value, not same reference
|
||||||
|
expect(p1.data.children).not.toBe(p2.data.children);
|
||||||
|
expect(p1.data.children).toEqual(p2.data.children);
|
||||||
|
|
||||||
|
// Add nodes to children
|
||||||
|
const p1_data = p1.data as PhaseNodeData;
|
||||||
|
const p2_data = p2.data as PhaseNodeData;
|
||||||
|
p1_data.children.push("norm-1");
|
||||||
|
p2_data.children.push("norm-2");
|
||||||
|
p2_data.children.push("goal-1");
|
||||||
|
|
||||||
|
// check that after adding, its not the same reference, and its not the same children
|
||||||
|
expect(p1.data.children).not.toBe(p2.data.children);
|
||||||
|
expect(p1.data.children).not.toEqual(p2.data.children);
|
||||||
|
|
||||||
|
// expect them to have the correct length.
|
||||||
|
expect(p1_data.children.length == 1);
|
||||||
|
expect(p2_data.children.length == 2);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -2,8 +2,11 @@ import { describe, it } from '@jest/globals';
|
|||||||
import '@testing-library/jest-dom';
|
import '@testing-library/jest-dom';
|
||||||
import { screen } from '@testing-library/react';
|
import { screen } from '@testing-library/react';
|
||||||
import type { Node } from '@xyflow/react';
|
import type { Node } from '@xyflow/react';
|
||||||
import { renderWithProviders } from '../.././/./../../test-utils/test-utils';
|
import { renderWithProviders } from '../../../../test-utils/test-utils.tsx';
|
||||||
import StartNode, { StartReduce, StartConnects } from '../../../../../src/pages/VisProgPage/visualProgrammingUI/nodes/StartNode';
|
import StartNode, {
|
||||||
|
StartConnectionSource, StartConnectionTarget,
|
||||||
|
StartReduce
|
||||||
|
} from '../../../../../src/pages/VisProgPage/visualProgrammingUI/nodes/StartNode';
|
||||||
|
|
||||||
|
|
||||||
describe('StartNode', () => {
|
describe('StartNode', () => {
|
||||||
@@ -91,8 +94,8 @@ describe('StartNode', () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
expect(() => StartConnects(startNode, otherNode, true)).not.toThrow();
|
expect(() => StartConnectionSource(startNode, otherNode.id)).not.toThrow();
|
||||||
expect(() => StartConnects(startNode, otherNode, false)).not.toThrow();
|
expect(() => StartConnectionTarget(startNode, otherNode.id)).not.toThrow();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,8 +1,13 @@
|
|||||||
import { describe, it, beforeEach } from '@jest/globals';
|
import { describe, it, beforeEach } from '@jest/globals';
|
||||||
import { screen, waitFor } from '@testing-library/react';
|
import { screen, waitFor } from '@testing-library/react';
|
||||||
import userEvent from '@testing-library/user-event';
|
import userEvent from '@testing-library/user-event';
|
||||||
import { renderWithProviders } from '../.././/./../../test-utils/test-utils';
|
import { renderWithProviders } from '../../../../test-utils/test-utils.tsx';
|
||||||
import TriggerNode, { TriggerReduce, TriggerConnects, TriggerNodeCanConnect, type TriggerNodeData } from '../../../../../src/pages/VisProgPage/visualProgrammingUI/nodes/TriggerNode';
|
import TriggerNode, {
|
||||||
|
TriggerReduce,
|
||||||
|
TriggerNodeCanConnect,
|
||||||
|
type TriggerNodeData,
|
||||||
|
TriggerConnectionSource, TriggerConnectionTarget
|
||||||
|
} from '../../../../../src/pages/VisProgPage/visualProgrammingUI/nodes/TriggerNode';
|
||||||
import useFlowStore from '../../../../../src/pages/VisProgPage/visualProgrammingUI/VisProgStores';
|
import useFlowStore from '../../../../../src/pages/VisProgPage/visualProgrammingUI/VisProgStores';
|
||||||
import type { Node } from '@xyflow/react';
|
import type { Node } from '@xyflow/react';
|
||||||
import '@testing-library/jest-dom';
|
import '@testing-library/jest-dom';
|
||||||
@@ -233,8 +238,8 @@ describe('TriggerNode', () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
expect(() => {
|
expect(() => {
|
||||||
TriggerConnects(node1, node2, true);
|
TriggerConnectionSource(node1, node2.id);
|
||||||
TriggerConnects(node1, node2, false);
|
TriggerConnectionTarget(node1, node2.id);
|
||||||
}).not.toThrow();
|
}).not.toThrow();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { describe, beforeEach } from '@jest/globals';
|
import { describe, beforeEach } from '@jest/globals';
|
||||||
import { screen } from '@testing-library/react';
|
import { screen } from '@testing-library/react';
|
||||||
import { renderWithProviders } from '../.././/./../../test-utils/test-utils';
|
import { renderWithProviders } from '../../../../test-utils/test-utils.tsx';
|
||||||
import type { XYPosition } from '@xyflow/react';
|
import type { XYPosition } from '@xyflow/react';
|
||||||
import { NodeTypes, NodeDefaults, NodeConnects, NodeReduces, NodesInPhase } from '../../../../../src/pages/VisProgPage/visualProgrammingUI/NodeRegistry';
|
import { NodeTypes, NodeDefaults, NodeConnections, NodeReduces, NodesInPhase } from '../../../../../src/pages/VisProgPage/visualProgrammingUI/NodeRegistry';
|
||||||
import '@testing-library/jest-dom'
|
import '@testing-library/jest-dom'
|
||||||
import { createElement } from 'react';
|
import { createElement } from 'react';
|
||||||
import useFlowStore from '../../../../../src/pages/VisProgPage/visualProgrammingUI/VisProgStores';
|
import useFlowStore from '../../../../../src/pages/VisProgPage/visualProgrammingUI/VisProgStores';
|
||||||
@@ -87,8 +87,8 @@ describe('NormNode', () => {
|
|||||||
useFlowStore.setState({ nodes: [sourceNode, targetNode] });
|
useFlowStore.setState({ nodes: [sourceNode, targetNode] });
|
||||||
|
|
||||||
// Spy on the connect functions
|
// Spy on the connect functions
|
||||||
const sourceConnectSpy = jest.spyOn(NodeConnects, nodeType as keyof typeof NodeConnects);
|
const sourceConnectSpy = jest.spyOn(NodeConnections.Sources, nodeType as keyof typeof NodeConnections.Sources);
|
||||||
const targetConnectSpy = jest.spyOn(NodeConnects, 'end');
|
const targetConnectSpy = jest.spyOn(NodeConnections.Targets, 'end');
|
||||||
|
|
||||||
// Simulate connection
|
// Simulate connection
|
||||||
useFlowStore.getState().onConnect({
|
useFlowStore.getState().onConnect({
|
||||||
@@ -99,8 +99,8 @@ describe('NormNode', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Verify the connect functions were called
|
// Verify the connect functions were called
|
||||||
expect(sourceConnectSpy).toHaveBeenCalledWith(sourceNode, targetNode, true);
|
expect(sourceConnectSpy).toHaveBeenCalledWith(sourceNode, targetNode.id);
|
||||||
expect(targetConnectSpy).toHaveBeenCalledWith(targetNode, sourceNode, false);
|
expect(targetConnectSpy).toHaveBeenCalledWith(targetNode, sourceNode.id);
|
||||||
|
|
||||||
sourceConnectSpy.mockRestore();
|
sourceConnectSpy.mockRestore();
|
||||||
targetConnectSpy.mockRestore();
|
targetConnectSpy.mockRestore();
|
||||||
@@ -130,7 +130,7 @@ describe('NormNode', () => {
|
|||||||
expect(phaseReduceSpy).toHaveBeenCalledWith(phaseNode, [phaseNode, testNode]);
|
expect(phaseReduceSpy).toHaveBeenCalledWith(phaseNode, [phaseNode, testNode]);
|
||||||
// Check if this node type is in NodesInPhase and returns false
|
// Check if this node type is in NodesInPhase and returns false
|
||||||
const nodesInPhaseFunc = NodesInPhase[nodeType as keyof typeof NodesInPhase];
|
const nodesInPhaseFunc = NodesInPhase[nodeType as keyof typeof NodesInPhase];
|
||||||
if (nodesInPhaseFunc && nodesInPhaseFunc() === false && nodeType !== 'phase') {
|
if (nodesInPhaseFunc && !nodesInPhaseFunc() && nodeType !== 'phase') {
|
||||||
// Node is NOT in phase, so it should NOT be called
|
// Node is NOT in phase, so it should NOT be called
|
||||||
expect(nodeReduceSpy).not.toHaveBeenCalled();
|
expect(nodeReduceSpy).not.toHaveBeenCalled();
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -2,6 +2,11 @@ import '@testing-library/jest-dom';
|
|||||||
import { cleanup } from '@testing-library/react';
|
import { cleanup } from '@testing-library/react';
|
||||||
import useFlowStore from '../src/pages/VisProgPage/visualProgrammingUI/VisProgStores.tsx';
|
import useFlowStore from '../src/pages/VisProgPage/visualProgrammingUI/VisProgStores.tsx';
|
||||||
|
|
||||||
|
if (!globalThis.structuredClone) {
|
||||||
|
globalThis.structuredClone = (obj: any) => {
|
||||||
|
return JSON.parse(JSON.stringify(obj));
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// To make sure that the tests are working, it's important that you are using
|
// To make sure that the tests are working, it's important that you are using
|
||||||
// this implementation of ResizeObserver and DOMMatrixReadOnly
|
// this implementation of ResizeObserver and DOMMatrixReadOnly
|
||||||
|
|||||||
100
test/utils/programStore.test.ts
Normal file
100
test/utils/programStore.test.ts
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
import useProgramStore, {type ReducedProgram} from "../../src/utils/programStore.ts";
|
||||||
|
|
||||||
|
|
||||||
|
describe('useProgramStore', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
// Reset store before each test
|
||||||
|
useProgramStore.setState({
|
||||||
|
currentProgram: { phases: [] },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const mockProgram: ReducedProgram = {
|
||||||
|
phases: [
|
||||||
|
{
|
||||||
|
id: 'phase-1',
|
||||||
|
norms: [{ id: 'norm-1' }],
|
||||||
|
goals: [{ id: 'goal-1' }],
|
||||||
|
triggers: [{ id: 'trigger-1' }],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'phase-2',
|
||||||
|
norms: [{ id: 'norm-2' }],
|
||||||
|
goals: [{ id: 'goal-2' }],
|
||||||
|
triggers: [{ id: 'trigger-2' }],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
it('should set and get the program state', () => {
|
||||||
|
useProgramStore.getState().setProgramState(mockProgram);
|
||||||
|
|
||||||
|
const program = useProgramStore.getState().getProgramState();
|
||||||
|
expect(program).toEqual(mockProgram);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return the ids of all phases in the program', () => {
|
||||||
|
useProgramStore.getState().setProgramState(mockProgram);
|
||||||
|
|
||||||
|
const phaseIds = useProgramStore.getState().getPhaseIds();
|
||||||
|
expect(phaseIds).toEqual(['phase-1', 'phase-2']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return all norms for a given phase', () => {
|
||||||
|
useProgramStore.getState().setProgramState(mockProgram);
|
||||||
|
|
||||||
|
const norms = useProgramStore.getState().getNormsInPhase('phase-1');
|
||||||
|
expect(norms).toEqual([{ id: 'norm-1' }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return all goals for a given phase', () => {
|
||||||
|
useProgramStore.getState().setProgramState(mockProgram);
|
||||||
|
|
||||||
|
const goals = useProgramStore.getState().getGoalsInPhase('phase-2');
|
||||||
|
expect(goals).toEqual([{ id: 'goal-2' }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return all triggers for a given phase', () => {
|
||||||
|
useProgramStore.getState().setProgramState(mockProgram);
|
||||||
|
|
||||||
|
const triggers = useProgramStore.getState().getTriggersInPhase('phase-1');
|
||||||
|
expect(triggers).toEqual([{ id: 'trigger-1' }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws if phase does not exist when getting norms', () => {
|
||||||
|
useProgramStore.getState().setProgramState(mockProgram);
|
||||||
|
|
||||||
|
expect(() =>
|
||||||
|
useProgramStore.getState().getNormsInPhase('missing-phase')
|
||||||
|
).toThrow('phase with id:"missing-phase" not found');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws if phase does not exist when getting goals', () => {
|
||||||
|
useProgramStore.getState().setProgramState(mockProgram);
|
||||||
|
|
||||||
|
expect(() =>
|
||||||
|
useProgramStore.getState().getGoalsInPhase('missing-phase')
|
||||||
|
).toThrow('phase with id:"missing-phase" not found');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws if phase does not exist when getting triggers', () => {
|
||||||
|
useProgramStore.getState().setProgramState(mockProgram);
|
||||||
|
|
||||||
|
expect(() =>
|
||||||
|
useProgramStore.getState().getTriggersInPhase('missing-phase')
|
||||||
|
).toThrow('phase with id:"missing-phase" not found');
|
||||||
|
});
|
||||||
|
|
||||||
|
// this test should be at the bottom to avoid conflicts with the previous tests
|
||||||
|
it('should clone program state when setting it (no shared references should exist)', () => {
|
||||||
|
useProgramStore.getState().setProgramState(mockProgram);
|
||||||
|
|
||||||
|
const storedProgram = useProgramStore.getState().getProgramState();
|
||||||
|
|
||||||
|
// mutate original
|
||||||
|
(mockProgram.phases[0].norms as any[]).push({ id: 'norm-mutated' });
|
||||||
|
|
||||||
|
// store should NOT change
|
||||||
|
expect(storedProgram.phases[0]['norms']).toHaveLength(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user