-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree-builder.js
More file actions
463 lines (395 loc) · 16.8 KB
/
Copy pathtree-builder.js
File metadata and controls
463 lines (395 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
/**
* Tree Builder for Curriculum Browser
* Handles the visualization of hierarchical curriculum structures
*/
// Simple label cache to avoid repeated queries
const labelCache = new Map();
/**
* Render a tree structure in the DOM
* @param {Object} treeData - Tree data structure
* @param {HTMLElement} container - Container element to render into
* @param {Object} options - Rendering options
*/
async function renderTree(treeData, container, options = {}) {
const { maxDepth = 5, showLabels = true } = options;
// Clear container
container.innerHTML = '';
if (!treeData || (!treeData.children && !treeData.id)) {
container.innerHTML = '<p class="placeholder">No tree data available</p>';
return;
}
// Create root element
const rootElement = await createTreeNode(treeData, 0, maxDepth, showLabels);
container.appendChild(rootElement);
}
/**
* Create a tree node element
* @param {Object} nodeData - Node data
* @param {number} depth - Current depth in tree
* @param {number} maxDepth - Maximum depth to render
* @param {boolean} showLabels - Whether to fetch and show labels
* @returns {HTMLElement} - Tree node element
*/
async function createTreeNode(nodeData, depth, maxDepth, showLabels) {
const nodeElement = document.createElement('div');
nodeElement.className = 'tree-node';
// Create content container
const contentElement = document.createElement('div');
contentElement.className = 'tree-content';
// Add expand/collapse toggle if node has children
if (nodeData.children && nodeData.children.length > 0 && depth < maxDepth) {
const toggleElement = document.createElement('span');
toggleElement.className = 'tree-toggle';
toggleElement.textContent = '▶';
toggleElement.onclick = () => toggleNode(nodeElement);
contentElement.appendChild(toggleElement);
} else if (depth >= maxDepth && nodeData.children && nodeData.children.length > 0) {
const ellipsisElement = document.createElement('span');
ellipsisElement.className = 'tree-toggle';
ellipsisElement.textContent = '…';
ellipsisElement.title = `${nodeData.children.length} more items`;
contentElement.appendChild(ellipsisElement);
}
// Add node content
let label = nodeData.id;
if (showLabels && nodeData.id) {
try {
label = await window.SPARQLExamples.queryLabel(nodeData.id);
} catch (error) {
console.warn('Could not fetch label for:', nodeData.id);
}
}
const labelElement = document.createElement('span');
labelElement.textContent = label;
labelElement.title = nodeData.id; // Show full URI on hover
contentElement.appendChild(labelElement);
nodeElement.appendChild(contentElement);
// Add children container
if (nodeData.children && nodeData.children.length > 0 && depth < maxDepth) {
const childrenContainer = document.createElement('div');
childrenContainer.className = 'tree-children hidden';
// Create child nodes
for (const child of nodeData.children) {
const childElement = await createTreeNode(child, depth + 1, maxDepth, showLabels);
childrenContainer.appendChild(childElement);
}
nodeElement.appendChild(childrenContainer);
}
return nodeElement;
}
/**
* Toggle expand/collapse of a tree node
* @param {HTMLElement} nodeElement - Tree node element
*/
function toggleNode(nodeElement) {
const childrenContainer = nodeElement.querySelector('.tree-children');
const toggleElement = nodeElement.querySelector('.tree-toggle');
if (childrenContainer && toggleElement) {
const isHidden = childrenContainer.classList.contains('hidden');
if (isHidden) {
childrenContainer.classList.remove('hidden');
toggleElement.textContent = '▼';
nodeElement.classList.add('expanded');
} else {
childrenContainer.classList.add('hidden');
toggleElement.textContent = '▶';
nodeElement.classList.remove('expanded');
}
}
}
/**
* Expand all nodes in a tree
* @param {HTMLElement} container - Tree container element
*/
function expandAll(container) {
const hiddenChildren = container.querySelectorAll('.tree-children.hidden');
const toggles = container.querySelectorAll('.tree-toggle');
hiddenChildren.forEach(children => children.classList.remove('hidden'));
toggles.forEach(toggle => {
if (toggle.textContent === '▶') {
toggle.textContent = '▼';
}
});
const nodes = container.querySelectorAll('.tree-node');
nodes.forEach(node => node.classList.add('expanded'));
}
/**
* Collapse all nodes in a tree
* @param {HTMLElement} container - Tree container element
*/
function collapseAll(container) {
const visibleChildren = container.querySelectorAll('.tree-children:not(.hidden)');
const toggles = container.querySelectorAll('.tree-toggle');
visibleChildren.forEach(children => children.classList.add('hidden'));
toggles.forEach(toggle => {
if (toggle.textContent === '▼') {
toggle.textContent = '▶';
}
});
const nodes = container.querySelectorAll('.tree-node');
nodes.forEach(node => node.classList.remove('expanded'));
}
/**
* Create a tree node with lazy loading for children
* @param {string} nodeUri - URI of the node
* @param {number} depth - Current depth in tree
* @param {number} maxDepth - Maximum depth to render
* @param {boolean} showLabels - Whether to fetch and show labels
* @returns {HTMLElement} - Tree node element
*/
async function createTreeNodeWithLazyLoading(nodeUri, depth, maxDepth, showLabels) {
const nodeElement = document.createElement('div');
nodeElement.className = 'tree-node';
// Create content container
const contentElement = document.createElement('div');
contentElement.className = 'tree-content';
// Get children to determine if we need a toggle
let children = [];
let hasChildren = false;
try {
children = await window.SPARQLExamples.queryChildren(nodeUri);
hasChildren = children.length > 0;
console.log(`Node ${nodeUri} has ${children.length} children`);
} catch (error) {
console.warn('Could not fetch children for:', nodeUri, error);
}
// Add expand/collapse toggle if node has children and we're not at max depth
if (hasChildren && depth < maxDepth) {
const toggleElement = document.createElement('span');
toggleElement.className = 'tree-toggle';
toggleElement.textContent = '▶';
toggleElement.onclick = () => toggleNodeWithLazyLoading(nodeElement, nodeUri, depth, maxDepth, showLabels);
contentElement.appendChild(toggleElement);
} else if (depth >= maxDepth && hasChildren) {
const ellipsisElement = document.createElement('span');
ellipsisElement.className = 'tree-toggle';
ellipsisElement.textContent = '…';
ellipsisElement.title = `${children.length} more items`;
contentElement.appendChild(ellipsisElement);
}
// Add node content with loading state
const labelElement = document.createElement('span');
labelElement.textContent = 'Loading...'; // Initial loading text
labelElement.title = nodeUri; // Show full URI on hover
contentElement.appendChild(labelElement);
// Fetch and display label asynchronously with caching
if (showLabels && nodeUri) {
// Check cache first
if (labelCache.has(nodeUri)) {
const cachedLabel = labelCache.get(nodeUri);
labelElement.textContent = cachedLabel;
console.log(`Cached label for ${nodeUri}: ${cachedLabel}`);
} else {
try {
const fetchedLabel = await window.SPARQLExamples.queryLabel(nodeUri);
labelElement.textContent = fetchedLabel;
// Cache the label for future use
labelCache.set(nodeUri, fetchedLabel);
console.log(`Fetched and cached label for ${nodeUri}: ${fetchedLabel}`);
} catch (error) {
console.warn('Could not fetch label for:', nodeUri, error);
// Fallback to URI if label fetch fails
const fallbackLabel = nodeUri.split('/').pop() || nodeUri;
labelElement.textContent = fallbackLabel;
// Cache the fallback as well to avoid repeated failures
labelCache.set(nodeUri, fallbackLabel);
}
}
} else {
// If labels are disabled, show URI immediately
const uriLabel = nodeUri.split('/').pop() || nodeUri;
labelElement.textContent = uriLabel;
// Cache URI fallback for consistency
if (!labelCache.has(nodeUri)) {
labelCache.set(nodeUri, uriLabel);
}
}
nodeElement.appendChild(contentElement);
return nodeElement;
}
/**
* Toggle expand/collapse of a tree node with lazy loading
* @param {HTMLElement} nodeElement - Tree node element
* @param {string} nodeUri - URI of the node
* @param {number} depth - Current depth in tree
* @param {number} maxDepth - Maximum depth to render
* @param {boolean} showLabels - Whether to fetch and show labels
*/
async function toggleNodeWithLazyLoading(nodeElement, nodeUri, depth, maxDepth, showLabels) {
const toggleElement = nodeElement.querySelector('.tree-toggle');
let childrenContainer = nodeElement.querySelector('.tree-children');
if (!childrenContainer) {
// Create children container if it doesn't exist
childrenContainer = document.createElement('div');
childrenContainer.className = 'tree-children hidden';
nodeElement.appendChild(childrenContainer);
// Load children
try {
const children = await window.SPARQLExamples.queryChildren(nodeUri);
console.log(`Loading ${children.length} children for ${nodeUri}`);
// Create child nodes
for (const childUri of children) {
const childElement = await createTreeNodeWithLazyLoading(childUri, depth + 1, maxDepth, showLabels);
childrenContainer.appendChild(childElement);
}
} catch (error) {
console.error('Error loading children for:', nodeUri, error);
childrenContainer.innerHTML = '<div class="error">Error loading children</div>';
}
}
// Toggle visibility
const isHidden = childrenContainer.classList.contains('hidden');
if (isHidden) {
childrenContainer.classList.remove('hidden');
toggleElement.textContent = '▼';
nodeElement.classList.add('expanded');
} else {
childrenContainer.classList.add('hidden');
toggleElement.textContent = '▶';
nodeElement.classList.remove('expanded');
}
}
/**
* Build tree from curriculum URI using simple incremental approach
* @param {string} curriculumUri - Root curriculum URI
* @param {HTMLElement} container - Container to render tree in
* @param {Object} options - Tree building options
*/
async function buildCurriculumTree(curriculumUri, container, options = {}) {
const { maxDepth = 5, showLabels = true } = options;
try {
// Show loading state
container.innerHTML = '<div class="loading"></div>Loading curriculum tree...';
console.log('Building tree for curriculum:', curriculumUri);
// Create root node with lazy loading
const rootNode = await createTreeNodeWithLazyLoading(curriculumUri, 0, maxDepth, showLabels);
// Clear container and render
container.innerHTML = '';
container.appendChild(rootNode);
console.log('Tree rendered successfully with lazy loading');
} catch (error) {
console.error('Error building curriculum tree:', error);
// Provide more detailed error information
let errorMessage = error.message;
if (error.message.includes('SPARQL query failed')) {
errorMessage = 'Unable to connect to the SPARQL endpoint. Please check your configuration.';
} else if (error.message.includes('NetworkError')) {
errorMessage = 'Network error. Please check your internet connection and endpoint URL.';
}
container.innerHTML = `<div class="error">Error loading tree: ${errorMessage}</div>`;
}
}
/**
* Build tree from flat SPARQL results (alternative approach)
* @param {Array} sparqlResults - Flat SPARQL query results
* @param {HTMLElement} container - Container to render tree in
* @param {Object} options - Tree building options
*/
async function buildTreeFromFlatResults(sparqlResults, container, options = {}) {
const { showLabels = true } = options;
try {
// Show loading state
container.innerHTML = '<div class="loading"></div>Building tree structure...';
// Build tree structure
const treeData = window.SPARQLExamples.buildTreeFromSPARQLResults(sparqlResults);
// Render tree
await renderTree(treeData, container, { showLabels });
} catch (error) {
console.error('Error building tree from flat results:', error);
container.innerHTML = `<div class="error">Error building tree: ${error.message}</div>`;
}
}
/**
* Create a simple tree visualization for demonstration
* @param {Object} treeData - Tree data structure
* @param {HTMLElement} container - Container element
* @param {number} depth - Current depth (for recursion)
*/
function createSimpleTreeVisualization(treeData, container, depth = 0) {
if (!treeData) return;
const item = document.createElement('div');
item.style.marginLeft = `${depth * 20}px`;
item.style.padding = '5px';
item.style.borderLeft = '2px solid #ddd';
item.style.marginBottom = '5px';
// Add toggle for children
if (treeData.children && treeData.children.length > 0) {
const toggle = document.createElement('span');
toggle.textContent = '▶';
toggle.style.cursor = 'pointer';
toggle.style.marginRight = '5px';
const childrenContainer = document.createElement('div');
childrenContainer.style.display = 'none';
toggle.onclick = () => {
if (childrenContainer.style.display === 'none') {
childrenContainer.style.display = 'block';
toggle.textContent = '▼';
} else {
childrenContainer.style.display = 'none';
toggle.textContent = '▶';
}
};
item.appendChild(toggle);
// Recursively add children
treeData.children.forEach(child => {
createSimpleTreeVisualization(child, childrenContainer, depth + 1);
});
item.appendChild(childrenContainer);
}
// Add node content
const content = document.createElement('span');
content.textContent = treeData.id ? treeData.id.split('/').pop() : 'Node';
item.appendChild(content);
container.appendChild(item);
}
/**
* Utility function to format SPARQL query for display
* @param {string} query - Raw SPARQL query
* @returns {string} - Formatted HTML
*/
function formatSPARQLQuery(query) {
return query
.replace(/PREFIX/g, '<span class="keyword">PREFIX</span>')
.replace(/SELECT/g, '<span class="keyword">SELECT</span>')
.replace(/WHERE/g, '<span class="keyword">WHERE</span>')
.replace(/FILTER/g, '<span class="keyword">FILTER</span>')
.replace(/ORDER BY/g, '<span class="keyword">ORDER BY</span>')
.replace(/LIMIT/g, '<span class="keyword">LIMIT</span>')
.replace(/DISTINCT/g, '<span class="keyword">DISTINCT</span>')
.replace(/BIND/g, '<span class="keyword">BIND</span>')
.replace(/GROUP BY/g, '<span class="keyword">GROUP BY</span>')
.replace(/SAMPLE/g, '<span class="keyword">SAMPLE</span>')
.replace(/\?/g, '<span class="variable">$&</span>')
.replace(/https:\/\/[^\s<>]+/g, '<span class="uri">$&</span>')
.replace(/<[^>]+>/g, '<span class="uri">$&</span>');
}
/**
* Display SPARQL query with syntax highlighting
* @param {string} query - SPARQL query to display
* @param {HTMLElement} container - Container element
*/
function displaySPARQLQuery(query, container) {
const formattedQuery = formatSPARQLQuery(query);
container.innerHTML = `<div class="sparql-query">${formattedQuery}</div>`;
}
/**
* Display JSON response data
* @param {Object} data - JSON data to display
* @param {HTMLElement} container - Container element
*/
function displayJSONResponse(data, container) {
const jsonString = JSON.stringify(data, null, 2);
container.innerHTML = `<pre class="api-json">${jsonString}</pre>`;
}
// Export functions for global use
window.TreeBuilder = {
renderTree,
buildCurriculumTree,
buildTreeFromFlatResults,
createSimpleTreeVisualization,
expandAll,
collapseAll,
displaySPARQLQuery,
displayJSONResponse,
formatSPARQLQuery
};