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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 1 addition & 21 deletions boneset-api/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,24 +89,16 @@
//app.listen(PORT, () => {
// console.log(`🚀 Server running on http://127.0.0.1:${PORT}`);
//});




const express = require("express");
const axios = require("axios");
const cors = require("cors");
const path = require("path");

const app = express();
const PORT = process.env.PORT || 8000;

app.use(cors());

const GITHUB_REPO = "https://raw.githubusercontent.com/oss-slu/DigitalBonesBox/data/DataPelvis/";
const BONESET_JSON_URL = `${GITHUB_REPO}boneset/bony_pelvis.json`;
const BONES_DIR_URL = `${GITHUB_REPO}bones/`;

async function fetchJSON(url) {
try {
const response = await axios.get(url);
Expand All @@ -116,63 +108,51 @@ async function fetchJSON(url) {
return null;
}
}

app.get("/", (req, res) => {
res.json({ message: "Welcome to the Boneset API (GitHub-Integrated)" });
});

app.get("/combined-data", async (req, res) => {
try {
const bonesetData = await fetchJSON(BONESET_JSON_URL);
if (!bonesetData) return res.status(500).json({ error: "Failed to load boneset data" });

const bonesets = [{ id: bonesetData.id, name: bonesetData.name }];
const bones = [];
const subbones = [];

for (const boneId of bonesetData.bones) {
const boneJsonUrl = `${BONES_DIR_URL}${boneId}.json`;
const boneData = await fetchJSON(boneJsonUrl);

if (boneData) {
bones.push({ id: boneData.id, name: boneData.name, boneset: bonesetData.id });
boneData.subBones.forEach(subBoneId => {
subbones.push({ id: subBoneId, name: subBoneId.replace(/_/g, " "), bone: boneData.id });
});
}
}

res.json({ bonesets, bones, subbones });

} catch (error) {
console.error("Error fetching combined data:", error.message);
res.status(500).json({ error: "Internal Server Error" });
}
});

// --- CORRECTED HTMX ENDPOINT ---
app.get("/api/description/", async (req, res) => { // Path changed here (no :boneId)
const { boneId } = req.query; // Changed from req.params to req.query
if (!boneId) {
return res.send(" "); // Send empty response if no boneId is provided
}
const GITHUB_DESC_URL = `https://raw.githubusercontent.com/oss-slu/DigitalBonesBox/data/DataPelvis/descriptions/${boneId}_description.json`;

try {
const response = await axios.get(GITHUB_DESC_URL);
const descriptionData = response.data;

let html = `<li><strong>${descriptionData.name}</strong></li>`;
descriptionData.description.forEach(point => {
html += `<li>${point}</li>`;
});
res.send(html);

} catch (error) {
res.send("<li>Description not available.</li>");
}
});

app.listen(PORT, () => {
console.log(`🚀 Server running on http://127.0.0.1:${PORT}`);
});
});
39 changes: 33 additions & 6 deletions templates/js/api.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,42 @@
// api.js - Centralized API configuration and data fetching

// Centralized API configuration
const API_CONFIG = {
BASE_URL: "http://127.0.0.1:8000",
ENDPOINTS: {
COMBINED_DATA: "/combined-data",
MOCK_BONE_DATA: "./js/mock-bone-data.json"
}
};

export async function fetchCombinedData() {
// --- CORRECTED: Use the full URL of the backend server ---
const API_URL = "http://127.0.0.1:8000/combined-data";
const API_URL = `${API_CONFIG.BASE_URL}${API_CONFIG.ENDPOINTS.COMBINED_DATA}`;

try {
const response = await fetch(API_URL);
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error("Error fetching combined data:", error);
alert("Failed to load data.");
return { bonesets: [], bones: [], subbones: [] };
throw error;
}
}
}

export async function fetchMockBoneData() {
try {
const response = await fetch(API_CONFIG.ENDPOINTS.MOCK_BONE_DATA);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error("Error fetching mock bone data:", error);
return null;
}
}

// Export configuration for other modules to use
export { API_CONFIG };
6 changes: 4 additions & 2 deletions templates/js/dropdowns.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,17 @@ import { loadDescription } from "./description.js";

export function populateBonesetDropdown(bonesets) {
const bonesetSelect = document.getElementById("boneset-select");
bonesetSelect.innerHTML = "<option value=\"\">--Please select a Boneset--</option>";
bonesets.forEach(set => {
bonesetSelect.innerHTML = "<option value=\"\">--Please select a Boneset--</option>";

bonesets.forEach(set => {
const option = document.createElement("option");
option.value = set.id;
option.textContent = set.name;
bonesetSelect.appendChild(option);
});
}


export function setupDropdownListeners(combinedData) {
const bonesetSelect = document.getElementById("boneset-select");
const boneSelect = document.getElementById("bone-select");
Expand Down
48 changes: 42 additions & 6 deletions templates/js/main.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,55 @@
import { fetchCombinedData } from "./api.js";
import { fetchCombinedData, fetchMockBoneData } from "./api.js";
import { populateBonesetDropdown, setupDropdownListeners } from "./dropdowns.js";
import { initializeSidebar } from "./sidebar.js";
import { setupNavigation, setBoneAndSubbones, disableButtons } from "./navigation.js";
import { loadDescription } from "./description.js"; // ✅ CORRECT function name
import { loadDescription } from "./description.js";
import { displayBoneData, clearViewer } from "./viewer.js";

let combinedData = { bonesets: [], bones: [], subbones: [] };
let mockBoneData = null;

/**
* Handles bone selection from dropdown
* @param {string} boneId - The ID of the selected bone
*/
function handleBoneSelection(boneId) {
if (!mockBoneData) {
console.log("Mock data not available");
return;
}

const bone = mockBoneData.bones.find(b => b.id === boneId);
if (!bone) {
console.log(`No mock data found for bone: ${boneId}`);
clearViewer();
return;
}

// Use the dedicated viewer module to display the bone
displayBoneData(bone);
}

document.addEventListener("DOMContentLoaded", async () => {
// 1. Sidebar behavior
initializeSidebar();

// 2. Fetch data and populate dropdowns
// 2. Load mock bone data using centralized API
mockBoneData = await fetchMockBoneData();

// 3. Fetch data and populate dropdowns
combinedData = await fetchCombinedData();
populateBonesetDropdown(combinedData.bonesets);
setupDropdownListeners(combinedData);

// 3. Hook up navigation buttons
// 4. Hook up navigation buttons
const prevButton = document.getElementById("prev-button");
const nextButton = document.getElementById("next-button");
const subboneDropdown = document.getElementById("subbone-select");
const boneDropdown = document.getElementById("bone-select");

setupNavigation(prevButton, nextButton, subboneDropdown, loadDescription);

// 4. Update navigation when bone changes
// 5. Update navigation when bone changes
boneDropdown.addEventListener("change", (event) => {
const selectedBone = event.target.value;

Expand All @@ -34,15 +60,25 @@ document.addEventListener("DOMContentLoaded", async () => {
setBoneAndSubbones(selectedBone, relatedSubbones);
populateSubboneDropdown(subboneDropdown, relatedSubbones);
disableButtons(prevButton, nextButton);

// Handle bone selection using dedicated function
if (selectedBone) {
handleBoneSelection(selectedBone);
} else {
clearViewer();
}
});

// 5. Auto-select the first boneset
// 6. Auto-select the first boneset
const boneset = combinedData.bonesets[0];
if (boneset) {
document.getElementById("boneset-select").value = boneset.id;
const event = new Event("change");
document.getElementById("boneset-select").dispatchEvent(event);
}

// 7. Initialize display
clearViewer();
});

function populateSubboneDropdown(dropdown, subbones) {
Expand Down
43 changes: 43 additions & 0 deletions templates/js/mock-bone-data.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
{
"bones": [
{
"id": "ischium",
"name": "Ischium",
"image_url": "https://via.placeholder.com/600x400/4A90E2/FFFFFF?text=Ischium+Bone",
"annotations": [
{
"text": "Ischial Tuberosity - Attachment point for hamstring muscles",
"position": { "x": 300, "y": 150 }
},
{
"text": "Ischial Spine - Forms part of the lesser sciatic notch",
"position": { "x": 250, "y": 100 }
},
{
"text": "Ischial Ramus - Forms part of the obturator foramen",
"position": { "x": 350, "y": 200 }
}
]
},
{
"id": "ilium",
"name": "Ilium",
"image_url": "https://via.placeholder.com/600x400/50C878/FFFFFF?text=Ilium+Bone",
"annotations": []
},
{
"id": "pubis",
"name": "Pubis",
"annotations": [
{
"text": "Pubic Symphysis - Joint where left and right pubic bones meet",
"position": { "x": 300, "y": 60 }
},
{
"text": "Superior Pubic Ramus - Upper branch of the pubis",
"position": { "x": 250, "y": 180 }
}
]
}
]
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The mock data file is well-structured and accurately mimics the expected format of a complete bone object. This is exactly what was needed for the frontend to be developed independently.

However, The mock file should include examples for a few different scenarios to help with testing. For instance, it should include an object for a bone that has no annotations and another for a bone that is missing an image_url. This will help us ensure the frontend handles these cases gracefully.
Please expand the mock data to include these edge cases so we can verify the frontend doesn't break when the data isn't perfect.

104 changes: 104 additions & 0 deletions templates/js/viewer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
// viewer.js - Dedicated module for managing viewer state and display

/**
* Displays bone image with error handling for broken URLs
* @param {Object} boneData - The bone object from mock data
*/
export function displayBoneImage(boneData) {
const boneImage = document.getElementById("bone-image");
if (!boneImage) {
console.error("Bone image element not found");
return;
}

if (boneData.image_url) {
boneImage.src = boneData.image_url;
boneImage.alt = `${boneData.name} bone image`;
boneImage.style.display = "block";

// Handle image load errors gracefully
boneImage.onerror = () => {
console.warn(`Failed to load image for ${boneData.name}: ${boneData.image_url}`);
boneImage.src = "https://via.placeholder.com/600x400/CCCCCC/666666?text=Image+Load+Failed";
boneImage.alt = `${boneData.name} - Image failed to load`;
};

// Clear any previous error handlers when image loads successfully
boneImage.onload = () => {
boneImage.onerror = null;
};
} else {
// Handle missing image_url
boneImage.src = "https://via.placeholder.com/600x400/CCCCCC/666666?text=No+Image+Available";
boneImage.alt = `${boneData.name} - No image available`;
boneImage.style.display = "block";
console.warn(`No image URL provided for bone: ${boneData.name}`);
}
}

/**
* Displays annotations list for the selected bone
* @param {Array} annotations - Array of annotation objects
*/
export function displayAnnotations(annotations) {
const annotationsOverlay = document.getElementById("annotations-overlay");
if (!annotationsOverlay) {
console.error("Annotations overlay element not found");
return;
}

// Clear previous annotations
annotationsOverlay.innerHTML = "";

if (!annotations || annotations.length === 0) {
annotationsOverlay.innerHTML = "<p>No annotations available for this bone.</p>";
return;
}

// Create annotation list
const annotationsList = document.createElement("ul");
annotationsList.className = "annotations-list";

annotations.forEach((annotation) => {
const listItem = document.createElement("li");
listItem.className = "annotation-item";
listItem.textContent = annotation.text;
annotationsList.appendChild(listItem);
});

annotationsOverlay.appendChild(annotationsList);
}

/**
* Main function to display complete bone data (image + annotations)
* @param {Object} boneData - The complete bone object
*/
export function displayBoneData(boneData) {
if (!boneData) {
console.error("No bone data provided to display");
return;
}

displayBoneImage(boneData);
displayAnnotations(boneData.annotations);
}

/**
* Clears the viewer display
*/
export function clearViewer() {
const boneImage = document.getElementById("bone-image");
const annotationsOverlay = document.getElementById("annotations-overlay");

if (boneImage) {
boneImage.src = "";
boneImage.alt = "";
boneImage.style.display = "none";
boneImage.onerror = null; // Clear error handlers
boneImage.onload = null;
}

if (annotationsOverlay) {
annotationsOverlay.innerHTML = "<p>Select a bone to view image and annotations.</p>";
}
}
Loading