Compare commits
19 Commits
4dcbe78abf
...
feat/monit
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6e1eb25bbc | ||
|
|
a1e242e391 | ||
|
|
c9df87929b | ||
|
|
57ebe724db | ||
|
|
794e638081 | ||
|
|
12ef2ef86e | ||
|
|
0fefefe7f0 | ||
|
|
9601f56ea9 | ||
|
|
873b1cfb0b | ||
|
|
4bd67debf3 | ||
|
|
e53e1a3958 | ||
|
|
7a89b0aedd | ||
|
|
7b05c7344c | ||
|
|
d80ced547c | ||
|
|
cd1aa84f89 | ||
|
|
469a6c7a69 | ||
|
|
b0a5e4770c | ||
|
|
f0fe520ea0 | ||
|
|
b10dbae488 |
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>
|
||||
)
|
||||
}
|
||||
184
src/pages/MonitoringPage/MonitoringPage.module.css
Normal file
184
src/pages/MonitoringPage/MonitoringPage.module.css
Normal file
@@ -0,0 +1,184 @@
|
||||
.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: #f5f5f5;
|
||||
font-family: Arial, sans-serif;
|
||||
}
|
||||
|
||||
/* HEADER */
|
||||
.experimentOverview {
|
||||
grid-area: header;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
background: #fff;
|
||||
padding: 1rem;
|
||||
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
|
||||
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: #ccc;
|
||||
}
|
||||
|
||||
.completed {
|
||||
background-color: #5cb85c;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.current {
|
||||
background-color: #f0ad4e;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.connected {
|
||||
color: green;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.disconnected {
|
||||
color: red;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.pausePlayInactive{
|
||||
background-color: gray;
|
||||
}
|
||||
|
||||
.pausePlayActive{
|
||||
background-color: green;
|
||||
}
|
||||
|
||||
.next {
|
||||
background-color: lightgray;
|
||||
}
|
||||
|
||||
.restartPhase{
|
||||
background-color: rgb(255, 123, 0);
|
||||
}
|
||||
|
||||
.restartExperiment{
|
||||
background-color: red;
|
||||
}
|
||||
|
||||
/* MAIN GRID */
|
||||
.phaseOverview {
|
||||
grid-area: main;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
grid-template-rows: repeat(2, auto);
|
||||
gap: 1rem;
|
||||
background: #fff;
|
||||
padding: 1rem;
|
||||
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.phaseBox {
|
||||
background: #f9f9f9;
|
||||
border: 1px solid #ddd;
|
||||
padding: 1rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.05);
|
||||
}
|
||||
|
||||
.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 #ddd;
|
||||
padding-bottom: 0.4rem;
|
||||
}
|
||||
|
||||
.checked::before {
|
||||
content: '✔️ ';
|
||||
}
|
||||
|
||||
/* LOGS */
|
||||
.logs {
|
||||
grid-area: logs;
|
||||
background: #fff;
|
||||
padding: 1rem;
|
||||
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.logs textarea {
|
||||
width: 100%;
|
||||
height: 200px;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
|
||||
/* FOOTER */
|
||||
.controlsSection {
|
||||
grid-area: footer;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
background: #fff;
|
||||
padding: 1rem;
|
||||
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.gestures,
|
||||
.speech,
|
||||
.directSpeech {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.speechInput {
|
||||
display: flex;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
|
||||
.speechInput input {
|
||||
flex: 1;
|
||||
padding: 0.5rem;
|
||||
border: 1px solid #ccc;
|
||||
}
|
||||
|
||||
.speechInput button {
|
||||
background: #007bff;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 0.5rem 1rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* 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;
|
||||
@@ -7,14 +7,16 @@ import {
|
||||
MarkerType,
|
||||
} from '@xyflow/react';
|
||||
import '@xyflow/react/dist/style.css';
|
||||
import {useEffect} from "react";
|
||||
import {useEffect, useState} from "react";
|
||||
import {useShallow} from 'zustand/react/shallow';
|
||||
import useProgramStore from "../../utils/programStore.ts";
|
||||
import {DndToolbar} from './visualProgrammingUI/components/DragDropSidebar.tsx';
|
||||
import useFlowStore from './visualProgrammingUI/VisProgStores.tsx';
|
||||
import type {FlowState} from './visualProgrammingUI/VisProgTypes.tsx';
|
||||
import styles from './VisProg.module.css'
|
||||
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 |--
|
||||
|
||||
@@ -138,7 +140,7 @@ function VisualProgrammingUI() {
|
||||
}
|
||||
|
||||
// currently outputs the prepared program to the console
|
||||
function runProgram() {
|
||||
function runProgramm() {
|
||||
const phases = graphReducer();
|
||||
const program = {phases}
|
||||
console.log(JSON.stringify(program, null, 2));
|
||||
@@ -152,6 +154,10 @@ function runProgram() {
|
||||
).then((res) => {
|
||||
if (!res.ok) throw new Error("Failed communicating with 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."));
|
||||
}
|
||||
|
||||
@@ -174,6 +180,27 @@ function graphReducer() {
|
||||
* @constructor
|
||||
*/
|
||||
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 onClick={() => setShowSimpleProgram(false)}>
|
||||
Back to Editor ◀
|
||||
</button>
|
||||
<MonitoringPage/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<VisualProgrammingUI/>
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,11 @@ import '@testing-library/jest-dom';
|
||||
import { cleanup } from '@testing-library/react';
|
||||
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
|
||||
// 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