-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy patheditor.js
More file actions
510 lines (444 loc) · 17.9 KB
/
Copy patheditor.js
File metadata and controls
510 lines (444 loc) · 17.9 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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
/*
*-------------------------------------------------------------------------------
* Copyright (C) 2025 philippe
* Copyright (C) 2025 Eclipse Foundation
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*-------------------------------------------------------------------------------
*/
document.addEventListener('DOMContentLoaded', () => {
document.body.classList.add('editor-page');
const GITHUB_API_URL = 'https://api.github.com/repos/openhwgroup/uap/contents/ips?ref=main';
const CATEGORIES_URL = 'cfg/categories.json';
const LICENSES_URL = 'cfg/licenses.json';
const fileSelector = document.getElementById('file-selector');
const loadBtn = document.getElementById('load-file-btn');
const createNewBtn = document.getElementById('create-new-btn');
const loadLocalBtn = document.getElementById('load-local-btn');
const localFileInput = document.getElementById('local-file-input');
const saveBtn = document.getElementById('save-json-btn');
const projectNameInput = document.getElementById('project-name-input');
const table = document.getElementById('data-table');
const thead = table.querySelector('thead');
const tbody = table.querySelector('tbody');
const tfoot = table.querySelector('tfoot');
let currentData = [];
let allowedCategories = [];
let allowedLicenses = [];
let allLicensesData = []; // Full license objects with both name and licenseId
const schemaColumns = ["Name", "Category", "URL", "License", "Status", "Description", "WI", "Partners", "Comment"];
// --- INITIALIZATION ---
async function initialize() {
await Promise.all([
loadCategories(),
loadLicenses(),
populateFileSelector()
]);
}
async function loadCategories() {
try {
const response = await fetch(CATEGORIES_URL);
allowedCategories = await response.json();
} catch (error) {
console.error('Failed to load categories:', error);
alert('Error: Could not load categories configuration.');
}
}
async function loadLicenses() {
try {
const response = await fetch(LICENSES_URL);
allLicensesData = await response.json();
// Extract licenseId values from the licenses array
allowedLicenses = allLicensesData.map(license => license.licenseId);
} catch (error) {
console.error('Failed to load licenses:', error);
alert('Error: Could not load licenses configuration.');
}
}
async function populateFileSelector() {
try {
const response = await fetch(GITHUB_API_URL);
const items = await response.json();
const jsonFiles = items.filter(i => i.type === 'file' && i.name.endsWith('.json'));
jsonFiles.forEach(file => {
const option = document.createElement('option');
option.value = file.download_url;
option.textContent = file.name;
fileSelector.appendChild(option);
});
} catch (error) {
console.error('Failed to load file list from GitHub:', error);
}
}
// --- DATA HANDLING ---
async function loadFileData(url) {
try {
const response = await fetch(url);
currentData = await response.json();
if (currentData.length > 0 && currentData[0].Project) {
projectNameInput.value = currentData[0].Project;
} else {
projectNameInput.value = '';
}
renderTable();
saveBtn.disabled = false;
projectNameInput.disabled = false;
} catch (error) {
console.error('Failed to load or parse JSON file:', error);
alert('Error loading file. Please check the console for details.');
}
}
function createNewFile() {
projectNameInput.value = '';
projectNameInput.disabled = false;
projectNameInput.focus();
currentData = [{}]; // Start with one empty row
renderTable();
saveBtn.disabled = false;
}
function addRow() {
currentData.push({});
renderTable();
}
function insertRowBelow(index) {
currentData.splice(index + 1, 0, {});
renderTable();
}
function deleteRow(index) {
if (currentData.length === 1) {
// If it's the last row, just clear its data instead of deleting it.
currentData[index] = {};
} else {
// Otherwise, delete the row.
currentData.splice(index, 1);
}
renderTable();
}
function updateData(index, key, value) {
// For keys that should be arrays, split by comma
if (['WI', 'Partners', 'Category', 'License'].includes(key)) {
currentData[index][key] = value.split(',').map(s => s.trim()).filter(Boolean);
} else {
currentData[index][key] = value;
}
}
function saveFile() {
const projectName = projectNameInput.value.trim();
if (!projectName) {
alert('Please enter a Project Name before saving.');
projectNameInput.focus();
return;
}
// --- Validation for "Name" field ---
const seenNames = new Set();
for (let i = 0; i < currentData.length; i++) {
const row = currentData[i];
const name = (row.Name || '').trim();
// 1. Check for empty names
if (!name) {
alert(`Error: The "Name" field in row ${i + 1} cannot be empty.`);
return; // Stop the save process
}
// 2. Check for duplicate names
if (seenNames.has(name)) {
alert(`Error: Duplicate "Name" found: "${name}". All names must be unique.`);
return; // Stop the save process
}
seenNames.add(name);
}
// Validation of the License field
for (let i = 0; i < currentData.length; i++) {
const row = currentData[i];
const licenseField = row.License || '';
const licenses = Array.isArray(licenseField) ? licenseField : [licenseField];
for (const license of licenses) {
const trimmedLicense = String(license).trim();
if (!trimmedLicense) continue;
// Check if license is in the allowed list
if (!allowedLicenses.includes(trimmedLicense)) {
alert(`Error: Invalid license value "${trimmedLicense}" found in row ${i + 1}.\n` +
`Please select a valid license from the dropdown list.\n` +
`Valid licenses: ${allowedLicenses.join(', ')}`);
return; // Stop the save process
}
}
}
const outputOrder = ["Name", "URL", "License", "Status", "Description", "Project", "WI", "Partners", "Comment", "Category"];
// Add the project name to every entry
const dataToSave = currentData.map(row => {
const newRow = { Project: projectName };
outputOrder.forEach(key => {
if (key !== 'Project') {
// Ensure all keys exist, defaulting to empty string or empty array
if (['WI', 'Partners', 'Category', 'License'].includes(key)) {
newRow[key] = row[key] || [];
} else {
newRow[key] = row[key] || '';
}
}
});
return newRow;
});
const jsonString = JSON.stringify(dataToSave, null, 2);
const blob = new Blob([jsonString], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${projectName}.json`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
// --- RENDERING ---
function renderTable() {
// Clear existing content
thead.innerHTML = '';
tbody.innerHTML = '';
// Render Header
const headerRow = document.createElement('tr');
const actionsHeader = document.createElement('th');
actionsHeader.className = 'row-actions-cell';
headerRow.appendChild(actionsHeader);
schemaColumns.forEach(col => {
const th = document.createElement('th');
th.textContent = col;
headerRow.appendChild(th);
});
thead.appendChild(headerRow);
makeResizable(headerRow);
// Render Body Rows
currentData.forEach((row, rowIndex) => {
const tr = document.createElement('tr');
// Add cell for hover actions
const actionTd = document.createElement('td');
actionTd.className = 'row-actions-cell';
actionTd.innerHTML = `<div class="row-actions-container"><button class="row-action-btn add" title="Insert row below" onclick="window.insertRowBelow(${rowIndex})">+</button><button class="row-action-btn delete" title="Delete this row" onclick="window.deleteRow(${rowIndex})">-</button></div>`;
tr.appendChild(actionTd);
schemaColumns.forEach(key => {
const td = document.createElement('td');
const value = row[key] || '';
if (key === 'Category') {
// Create a custom multi-select combobox
const container = document.createElement('div');
container.className = 'category-combobox-container';
const input = document.createElement('input');
input.type = 'text';
input.value = Array.isArray(value) ? value.join(', ') : value;
input.dataset.index = rowIndex;
input.dataset.key = key;
container.appendChild(input);
const dropdown = document.createElement('div');
dropdown.className = 'category-dropdown';
allowedCategories.forEach(category => {
const option = document.createElement('div');
option.textContent = category.name;
option.className = 'category-option';
option.addEventListener('mousedown', (e) => {
e.preventDefault(); // Prevent input from losing focus
const currentValues = input.value.split(',').map(s => s.trim()).filter(Boolean);
if (!currentValues.includes(category.name)) {
currentValues.push(category.name);
input.value = currentValues.join(', ') + ', '; // Add comma for next entry
// Manually trigger the input event to update the data model
input.dispatchEvent(new Event('input', { bubbles: true }));
// Set focus and move cursor to the end of the input
input.focus();
const end = input.value.length;
input.setSelectionRange(end, end);
}
});
dropdown.appendChild(option);
});
container.appendChild(dropdown);
td.appendChild(container);
input.addEventListener('focus', () => {
dropdown.style.display = 'block';
});
input.addEventListener('blur', () => {
// Delay hiding to allow click on dropdown options
setTimeout(() => {
dropdown.style.display = 'none';
}, 150);
});
input.addEventListener('input', () => {
const filterText = input.value.split(',').pop().trim().toLowerCase();
dropdown.querySelectorAll('.category-option').forEach(opt => {
opt.style.display = opt.textContent.toLowerCase().includes(filterText) ? 'block' : 'none';
});
});
} else if (key === 'License') {
const container = document.createElement('div');
container.className = 'license-combobox-container';
const input = document.createElement('input');
input.type = 'text';
input.value = Array.isArray(value) ? value.join(', ') : value;
input.dataset.index = rowIndex;
input.dataset.key = key;
container.appendChild(input);
const dropdown = document.createElement('div');
dropdown.className = 'license-dropdown';
allowedLicenses.forEach(licenseId => {
const licenseData = allLicensesData.find(l => l.licenseId === licenseId);
const option = document.createElement('div');
option.textContent = licenseId;
option.className = 'license-option';
option.dataset.licenseId = licenseId;
option.addEventListener('mousedown', (e) => {
e.preventDefault(); // Prevent input from losing focus
const currentValues = input.value.split(',').map(s => s.trim()).filter(Boolean);
if (!currentValues.includes(licenseId)) {
currentValues.push(licenseId);
input.value = currentValues.join(', ') + ', ';
// Manually trigger the input event to update the data model
input.dispatchEvent(new Event('input', { bubbles: true }));
// Set focus and move cursor to the end of the input
input.focus();
const end = input.value.length;
input.setSelectionRange(end, end);
}
});
dropdown.appendChild(option);
});
container.appendChild(dropdown);
td.appendChild(container);
input.addEventListener('focus', () => {
dropdown.style.display = 'block';
});
input.addEventListener('blur', () => {
// Delay hiding to allow click on dropdown options
setTimeout(() => {
dropdown.style.display = 'none';
}, 150);
});
input.addEventListener('input', () => {
const filterText = input.value.split(',').pop().trim().toLowerCase();
// Filter by licenseId or license name
dropdown.querySelectorAll('.license-option').forEach(opt => {
const licenseData = allLicensesData.find(l => l.licenseId === opt.dataset.licenseId);
const matchesLicenseId = opt.textContent.toLowerCase().includes(filterText);
const matchesName = licenseData && licenseData.name.toLowerCase().includes(filterText);
opt.style.display = (matchesLicenseId || matchesName) ? 'block' : 'none';
});
});
} else {
const input = document.createElement('input');
input.type = 'text';
input.value = Array.isArray(value) ? value.join(', ') : value;
input.dataset.index = rowIndex;
input.dataset.key = key;
td.appendChild(input);
}
tr.appendChild(td);
});
tbody.appendChild(tr);
});
}
// Expose functions to global scope so inline onclick handlers can find them
window.insertRowBelow = insertRowBelow;
window.deleteRow = deleteRow;
// --- EVENT LISTENERS ---
loadBtn.addEventListener('click', () => {
const selectedUrl = fileSelector.value;
if (selectedUrl) {
loadFileData(selectedUrl);
} else {
alert('Please select a file to load.');
}
});
createNewBtn.addEventListener('click', createNewFile);
saveBtn.addEventListener('click', saveFile);
loadLocalBtn.addEventListener('click', () => localFileInput.click());
localFileInput.addEventListener('change', (event) => {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (e) => {
try {
const data = JSON.parse(e.target.result);
currentData = Array.isArray(data) ? data : [data];
if (currentData.length > 0 && currentData[0].Project) {
projectNameInput.value = currentData[0].Project;
}
renderTable();
saveBtn.disabled = false;
projectNameInput.disabled = false;
} catch (err) {
alert(`Error parsing JSON file: ${err.message}`);
}
};
reader.readAsText(file);
});
// Use 'input' for text fields to update data instantly on every keystroke.
// Use 'change' for select dropdowns.
tbody.addEventListener('input', (e) => {
const target = e.target;
if (target.tagName === 'INPUT') {
const { index, key } = target.dataset;
updateData(parseInt(index, 10), key, target.value);
}
});
tbody.addEventListener('change', (e) => {
const target = e.target;
if (target.tagName === 'SELECT') {
const { index, key } = target.dataset;
updateData(parseInt(index, 10), key, target.value);
}
});
// --- START ---
initialize();
});
function makeResizable(headerRow) {
const table = headerRow.closest('table');
let cg = table.querySelector('colgroup');
if (!cg) {
cg = document.createElement('colgroup');
table.insertBefore(cg, headerRow.parentElement);
}
cg.innerHTML = ''; // Clear existing colgroup
const ths = Array.from(headerRow.children);
ths.forEach(() => cg.appendChild(document.createElement('col')));
const cols = Array.from(cg.children);
ths.forEach((th, i) => {
if (i === ths.length - 1) return; // No resizer on the last column
const resizer = document.createElement('div');
resizer.className = 'resizer';
th.appendChild(resizer);
resizer.tabIndex = 0;
resizer.setAttribute('role', 'separator');
resizer.setAttribute('aria-label', `Resize ${th.textContent}`);
let startX, startWidth;
const onPointerMove = e => {
const x = e.pageX ?? (e.touches && e.touches[0] && e.touches[0].pageX) ?? e.clientX;
const delta = x - startX;
cols[i].style.width = startWidth + delta + 'px';
};
const onPointerUp = e => {
document.removeEventListener('pointermove', onPointerMove);
document.removeEventListener('pointerup', onPointerUp);
try { resizer.releasePointerCapture && resizer.releasePointerCapture(e.pointerId); } catch(_) {}
};
resizer.addEventListener('pointerdown', e => {
e.preventDefault();
startX = e.pageX || e.clientX;
startWidth = th.offsetWidth;
try { resizer.setPointerCapture && resizer.setPointerCapture(e.pointerId); } catch(_) {}
document.addEventListener('pointermove', onPointerMove);
document.addEventListener('pointerup', onPointerUp);
});
resizer.addEventListener('keydown', e => {
const cur = parseInt(getComputedStyle(cols[i]).width, 10) || th.offsetWidth;
if (e.key === 'ArrowLeft') {
cols[i].style.width = Math.max(20, cur - 10) + 'px';
e.preventDefault();
} else if (e.key === 'ArrowRight') {
cols[i].style.width = (cur + 10) + 'px';
e.preventDefault();
}
});
});
}