-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1008 lines (829 loc) · 36.8 KB
/
script.js
File metadata and controls
1008 lines (829 loc) · 36.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
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
class CRDExplorer {
constructor() {
this.crds = new Map();
this.currentTab = null;
this.maxFileSize = 10 * 1024 * 1024; // 10MB limit
this.maxDepth = 50; // Prevent deeply nested objects
this.initializeEventListeners();
}
initializeEventListeners() {
const uploadArea = document.getElementById('uploadArea');
const fileInput = document.getElementById('fileInput');
uploadArea.addEventListener('click', (e) => {
if (e.target === fileInput) return;
fileInput.click();
});
uploadArea.addEventListener('dragover', this.handleDragOver.bind(this));
uploadArea.addEventListener('dragleave', this.handleDragLeave.bind(this));
uploadArea.addEventListener('drop', this.handleDrop.bind(this));
fileInput.addEventListener('change', this.handleFileSelect.bind(this));
// Search functionality
const searchInput = document.getElementById('searchInput');
const searchFilter = document.getElementById('searchFilter');
const clearSearch = document.getElementById('clearSearch');
const collapseToFirstLevel = document.getElementById('collapseToFirstLevel');
const toggleUpload = document.getElementById('toggleUpload');
if (searchInput) {
searchInput.addEventListener('input', this.handleSearch.bind(this));
searchFilter.addEventListener('change', this.handleSearch.bind(this));
clearSearch.addEventListener('click', this.clearSearch.bind(this));
collapseToFirstLevel.addEventListener('click', this.collapseToFirstLevel.bind(this));
toggleUpload.addEventListener('click', this.toggleUploadSection.bind(this));
}
// Modal functionality
const licensesLink = document.getElementById('licensesLink');
const licensesModal = document.getElementById('licensesModal');
const modalClose = document.getElementById('modalClose');
licensesLink.addEventListener('click', () => {
licensesModal.style.display = 'flex';
});
modalClose.addEventListener('click', () => {
licensesModal.style.display = 'none';
});
licensesModal.addEventListener('click', (e) => {
if (e.target === licensesModal) {
licensesModal.style.display = 'none';
}
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && licensesModal.style.display === 'flex') {
licensesModal.style.display = 'none';
}
});
}
handleDragOver(e) {
e.preventDefault();
e.currentTarget.classList.add('dragover');
}
handleDragLeave(e) {
e.preventDefault();
e.currentTarget.classList.remove('dragover');
}
handleDrop(e) {
e.preventDefault();
e.currentTarget.classList.remove('dragover');
const files = Array.from(e.dataTransfer.files);
this.processFiles(files);
}
handleFileSelect(e) {
const files = Array.from(e.target.files);
this.processFiles(files);
e.target.value = '';
}
async processFiles(files) {
const validFiles = files.filter(file =>
(file.name.endsWith('.yaml') ||
file.name.endsWith('.yml') ||
file.name.endsWith('.json')) &&
file.size <= this.maxFileSize
);
if (validFiles.length === 0) {
this.showError('Please select valid YAML or JSON files (max 10MB each)');
return;
}
const oversizedFiles = files.filter(file => file.size > this.maxFileSize);
if (oversizedFiles.length > 0) {
this.showError(`Files too large: ${oversizedFiles.map(f => f.name).join(', ')} (max 10MB)`);
return;
}
this.hideError();
for (const file of validFiles) {
try {
const content = await this.readFile(file);
const crds = this.parseCRD(content, file.name);
if (crds && crds.length > 0) {
// If multiple CRDs in one file, create unique keys for each
if (crds.length === 1) {
this.crds.set(file.name, crds[0]);
} else {
crds.forEach((crd, index) => {
const key = `${file.name} (${crd.metadata.name || `CRD ${index + 1}`})`;
this.crds.set(key, crd);
});
}
}
} catch (error) {
console.error(`Error processing ${file.name}:`, error);
this.showError(`Error processing ${file.name}: ${error.message}`);
}
}
this.renderTabs();
}
readFile(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = e => resolve(e.target.result);
reader.onerror = reject;
reader.readAsText(file);
});
}
parseCRD(content, filename) {
try {
// Validate content length
if (content.length > this.maxFileSize) {
throw new Error('Content too large');
}
let documents;
if (filename.endsWith('.json')) {
documents = [JSON.parse(content)];
} else {
// Safe YAML parsing with depth limit - support multiple documents
documents = jsyaml.loadAll(content, null, {
schema: jsyaml.CORE_SCHEMA,
onWarning: (warning) => console.warn('YAML Warning:', warning)
});
}
// Filter out null/undefined documents and validate each
const validCRDs = [];
documents.forEach((data, index) => {
if (!data) return; // Skip empty documents
// Validate structure depth
if (!this.validateObjectDepth(data, 0)) {
throw new Error(`Document ${index + 1}: Object structure too deeply nested`);
}
// Validate required CRD fields
if (!data || typeof data !== 'object') {
throw new Error(`Document ${index + 1}: Invalid data structure`);
}
if (data.kind !== 'CustomResourceDefinition') {
throw new Error(`Document ${index + 1}: File is not a valid CustomResourceDefinition`);
}
// Basic structure validation
if (!data.metadata?.name || !data.spec?.group || !data.spec?.names) {
throw new Error(`Document ${index + 1}: Missing required CRD fields`);
}
validCRDs.push(this.sanitizeCRD(data));
});
if (validCRDs.length === 0) {
throw new Error('No valid CustomResourceDefinitions found');
}
return validCRDs;
} catch (error) {
throw new Error(`Failed to parse ${this.sanitizeFilename(filename)}: ${this.sanitizeError(error.message)}`);
}
}
renderTabs() {
const crdExplorerContainer = document.getElementById('crdExplorerContainer');
const uploadWrapper = document.getElementById('uploadWrapper');
const tabsContainer = document.getElementById('tabsContainer');
const tabs = document.getElementById('tabs');
const tabContent = document.getElementById('tabContent');
if (this.crds.size === 0) {
crdExplorerContainer.style.display = 'none';
uploadWrapper.classList.remove('hidden');
return;
}
crdExplorerContainer.style.display = 'block';
// Auto-hide upload section when files are loaded
uploadWrapper.classList.add('hidden');
tabs.innerHTML = '';
let isFirst = true;
for (const [filename, crd] of this.crds) {
const tab = document.createElement('button');
tab.className = `tab ${isFirst ? 'active' : ''}`;
tab.textContent = this.sanitizeText(crd.metadata.name || filename);
tab.addEventListener('click', () => this.switchTab(filename));
tabs.appendChild(tab);
if (isFirst) {
this.currentTab = filename;
this.renderCRD(crd);
isFirst = false;
}
}
}
switchTab(filename) {
document.querySelectorAll('.tab').forEach(tab => tab.classList.remove('active'));
event.target.classList.add('active');
this.currentTab = filename;
const crd = this.crds.get(filename);
this.renderCRD(crd);
// Reapply current search if one exists
this.reapplySearch();
}
renderCRD(crd) {
const tabContent = document.getElementById('tabContent');
const container = document.createElement('div');
// Create CRD info section
const crdInfo = document.createElement('div');
crdInfo.className = 'crd-info';
const title = document.createElement('h2');
title.className = 'crd-title';
title.textContent = this.sanitizeText(crd.metadata.name);
crdInfo.appendChild(title);
const crdMeta = document.createElement('div');
crdMeta.className = 'crd-meta';
const metaItems = [
['API Version', crd.apiVersion],
['Group', crd.spec.group],
['Scope', crd.spec.scope],
['Kind', crd.spec.names.kind],
['Plural', crd.spec.names.plural],
['Singular', crd.spec.names.singular]
];
metaItems.forEach(([label, value]) => {
const metaItem = document.createElement('div');
metaItem.className = 'meta-item';
const metaLabel = document.createElement('span');
metaLabel.className = 'meta-label';
metaLabel.textContent = label;
const metaValue = document.createElement('span');
metaValue.className = 'meta-value';
metaValue.textContent = this.sanitizeText(value);
metaItem.appendChild(metaLabel);
metaItem.appendChild(metaValue);
crdMeta.appendChild(metaItem);
});
crdInfo.appendChild(crdMeta);
container.appendChild(crdInfo);
// Create schema tree section
const schemaTree = document.createElement('div');
schemaTree.className = 'schema-tree';
const schemaTitle = document.createElement('h3');
schemaTitle.textContent = 'Schema Documentation';
schemaTree.appendChild(schemaTitle);
const versionsElement = this.renderVersions(crd);
schemaTree.appendChild(versionsElement);
container.appendChild(schemaTree);
// Clear and append safely
tabContent.textContent = '';
tabContent.appendChild(container);
this.initializeTreeInteraction();
}
renderVersions(crd) {
const container = document.createElement('div');
if (!crd.spec.versions || crd.spec.versions.length === 0) {
const noVersions = document.createElement('p');
noVersions.textContent = 'No schema versions found';
container.appendChild(noVersions);
return container;
}
crd.spec.versions.forEach(version => {
const versionSection = document.createElement('div');
versionSection.className = 'version-section';
const versionTitle = document.createElement('h4');
versionTitle.textContent = `Version: ${this.sanitizeText(version.name)}`;
versionSection.appendChild(versionTitle);
if (!version.schema || !version.schema.openAPIV3Schema) {
const noSchema = document.createElement('p');
noSchema.textContent = 'No schema defined for this version';
versionSection.appendChild(noSchema);
} else {
const schema = version.schema.openAPIV3Schema;
const rootRequired = schema.required || [];
const schemaNode = this.renderSchemaNode('spec', schema.properties?.spec || {}, [], true, true, rootRequired);
versionSection.appendChild(schemaNode);
}
container.appendChild(versionSection);
});
return container;
}
renderSchemaNode(name, schema, path = [], isRoot = false, autoExpand = false, parentRequired = []) {
if (!schema || typeof schema !== 'object') {
return document.createElement('div');
}
const fullPath = [...path, name].join('.');
const hasChildren = (schema.properties && Object.keys(schema.properties).length > 0) ||
(schema.type === 'array' && schema.items && typeof schema.items === 'object');
const isRequired = parentRequired.includes(name);
const treeNode = document.createElement('div');
treeNode.className = 'tree-node';
treeNode.setAttribute('data-path', this.sanitizeAttribute(fullPath));
const propertyHeader = document.createElement('div');
propertyHeader.className = 'property-header';
// Create left container for expand icon, name, type, and required
const propertyLeft = document.createElement('div');
propertyLeft.className = 'property-left';
if (hasChildren) {
propertyHeader.onclick = () => this.toggleNode(propertyHeader);
const expandIcon = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
expandIcon.classList.add('expand-icon');
if (autoExpand) expandIcon.classList.add('expanded');
expandIcon.setAttribute('viewBox', '0 0 24 24');
expandIcon.setAttribute('fill', 'none');
expandIcon.setAttribute('stroke', 'currentColor');
expandIcon.setAttribute('stroke-width', '2');
const polyline = document.createElementNS('http://www.w3.org/2000/svg', 'polyline');
polyline.setAttribute('points', '9,18 15,12 9,6');
expandIcon.appendChild(polyline);
propertyLeft.appendChild(expandIcon);
}
const propertyName = document.createElement('span');
propertyName.className = 'property-name';
propertyName.textContent = this.sanitizeText(name);
propertyLeft.appendChild(propertyName);
if (schema.type) {
const propertyType = document.createElement('span');
propertyType.className = 'property-type';
propertyType.textContent = this.sanitizeText(schema.type);
propertyLeft.appendChild(propertyType);
}
if (isRequired) {
const requiredSpan = document.createElement('span');
requiredSpan.className = 'property-required';
requiredSpan.textContent = 'required';
propertyLeft.appendChild(requiredSpan);
}
// Create right container for the path
const propertyRight = document.createElement('div');
propertyRight.className = 'property-right';
const propertyPath = document.createElement('span');
propertyPath.className = 'property-path';
propertyPath.textContent = this.sanitizeText(this.formatPathForDisplay(fullPath));
propertyPath.setAttribute('title', this.sanitizeText(fullPath)); // Full path in tooltip
propertyRight.appendChild(propertyPath);
propertyHeader.appendChild(propertyLeft);
propertyHeader.appendChild(propertyRight);
treeNode.appendChild(propertyHeader);
if (schema.description) {
const description = document.createElement('div');
description.className = 'property-description';
description.textContent = this.sanitizeText(schema.description);
treeNode.appendChild(description);
}
if (this.hasAdditionalDetails(schema)) {
const details = this.renderPropertyDetails(schema);
treeNode.appendChild(details);
}
if (hasChildren) {
const propertyChildren = document.createElement('div');
propertyChildren.className = 'property-children';
if (autoExpand) propertyChildren.classList.add('expanded');
// Render object properties
if (schema.properties) {
const required = schema.required || [];
for (const [propName, propSchema] of Object.entries(schema.properties)) {
const childNode = this.renderSchemaNode(propName, propSchema, [...path, name], false, false, required);
propertyChildren.appendChild(childNode);
}
}
// Render array items schema
if (schema.type === 'array' && schema.items && typeof schema.items === 'object') {
const itemNode = this.renderSchemaNode('items', schema.items, [...path, name], false, false, []);
propertyChildren.appendChild(itemNode);
}
treeNode.appendChild(propertyChildren);
}
return treeNode;
}
hasAdditionalDetails(schema) {
return schema.format ||
schema.pattern ||
schema.minimum !== undefined ||
schema.maximum !== undefined ||
schema.minLength !== undefined ||
schema.maxLength !== undefined ||
schema.enum ||
schema.default !== undefined;
}
renderPropertyDetails(schema) {
let details = [];
if (schema.format) details.push(['Format', schema.format]);
if (schema.pattern) details.push(['Pattern', schema.pattern]);
if (schema.minimum !== undefined) details.push(['Minimum', schema.minimum]);
if (schema.maximum !== undefined) details.push(['Maximum', schema.maximum]);
if (schema.minLength !== undefined) details.push(['Min Length', schema.minLength]);
if (schema.maxLength !== undefined) details.push(['Max Length', schema.maxLength]);
if (schema.enum) details.push(['Allowed Values', Array.isArray(schema.enum) ? schema.enum.join(', ') : String(schema.enum)]);
if (schema.default !== undefined) details.push(['Default', this.sanitizeText(JSON.stringify(schema.default))]);
if (details.length === 0) {
return document.createElement('div');
}
const propertyDetails = document.createElement('div');
propertyDetails.className = 'property-details';
details.forEach(([label, value]) => {
const detailRow = document.createElement('div');
detailRow.className = 'detail-row';
const detailLabel = document.createElement('span');
detailLabel.className = 'detail-label';
detailLabel.textContent = `${label}:`;
const detailValue = document.createElement('span');
detailValue.className = 'detail-value';
detailValue.textContent = this.sanitizeText(String(value));
detailRow.appendChild(detailLabel);
detailRow.appendChild(detailValue);
propertyDetails.appendChild(detailRow);
});
return propertyDetails;
}
initializeTreeInteraction() {
// Method is now handled directly in renderSchemaNode
}
toggleNode(header) {
const node = header.parentElement;
const children = node.querySelector('.property-children');
const icon = header.querySelector('.expand-icon');
if (children) {
children.classList.toggle('expanded');
if (icon) {
icon.classList.toggle('expanded');
}
// If search is active and we're expanding, show all child nodes
const searchInput = document.getElementById('searchInput');
if (searchInput && searchInput.value.trim() && children.classList.contains('expanded')) {
this.showExpandedChildrenDuringSearch(children);
}
}
}
sanitizeText(text) {
if (typeof text !== 'string') {
text = String(text);
}
// Since we're using textContent (not innerHTML), we only need to prevent
// script injection, not HTML entities. Quotes are safe in textContent.
return text.replace(/[\u0000-\u001F\u007F-\u009F]/g, ''); // Remove control characters
}
sanitizeAttribute(text) {
if (typeof text !== 'string') {
text = String(text);
}
// Only allow alphanumeric, dots, hyphens, and underscores
return text.replace(/[^a-zA-Z0-9._-]/g, '_');
}
sanitizeFilename(filename) {
if (typeof filename !== 'string') {
filename = String(filename);
}
// Basic filename sanitization
return filename.replace(/[<>:"/\\|?*]/g, '_');
}
sanitizeError(error) {
if (typeof error !== 'string') {
error = String(error);
}
// Limit error message length and sanitize
return this.sanitizeText(error.substring(0, 200));
}
validateObjectDepth(obj, currentDepth) {
if (currentDepth > this.maxDepth) {
return false;
}
if (obj && typeof obj === 'object') {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
if (!this.validateObjectDepth(obj[key], currentDepth + 1)) {
return false;
}
}
}
}
return true;
}
sanitizeCRD(crd) {
// Deep clone to avoid modifying original
const sanitized = JSON.parse(JSON.stringify(crd));
// Remove any functions or undefined values that might have been injected
return this.removeUnsafeProperties(sanitized);
}
removeUnsafeProperties(obj) {
if (obj && typeof obj === 'object') {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const value = obj[key];
if (typeof value === 'function' || value === undefined) {
delete obj[key];
} else if (typeof value === 'object' && value !== null) {
this.removeUnsafeProperties(value);
}
}
}
}
return obj;
}
showExpandedChildrenDuringSearch(childrenContainer) {
// When manually expanding during search, show all immediate child nodes
const childNodes = childrenContainer.querySelectorAll(':scope > .tree-node');
childNodes.forEach(child => {
child.classList.remove('search-hidden');
});
}
showManuallyExpandedNodes() {
// Find all expanded property-children containers and show their immediate children
const tabContent = document.getElementById('tabContent');
if (!tabContent) return;
const expandedContainers = tabContent.querySelectorAll('.property-children.expanded');
expandedContainers.forEach(container => {
// Show the parent node (the one that was expanded)
const parentNode = container.closest('.tree-node');
if (parentNode) {
parentNode.classList.remove('search-hidden');
}
// Show all immediate child nodes
const childNodes = container.querySelectorAll(':scope > .tree-node');
childNodes.forEach(child => {
child.classList.remove('search-hidden');
});
});
}
collapseNodesWithoutMatches(matchingNodes) {
const tabContent = document.getElementById('tabContent');
if (!tabContent) return;
// Get all nodes that have children
const nodesWithChildren = tabContent.querySelectorAll('.tree-node .property-children');
nodesWithChildren.forEach(childrenContainer => {
const parentNode = childrenContainer.closest('.tree-node');
if (!parentNode) return;
// Check if this node or any of its descendants have matches
const hasMatchInSubtree = this.hasMatchInSubtree(parentNode, matchingNodes);
// If no matches in subtree, collapse this node
if (!hasMatchInSubtree) {
const expandIcon = parentNode.querySelector('.expand-icon');
if (childrenContainer.classList.contains('expanded')) {
childrenContainer.classList.remove('expanded');
if (expandIcon) {
expandIcon.classList.remove('expanded');
}
}
}
});
}
hasMatchInSubtree(node, matchingNodes) {
// Check if this node itself is a match
if (matchingNodes.includes(node)) {
return true;
}
// Check if any descendant is a match
const descendants = node.querySelectorAll('.tree-node');
for (const descendant of descendants) {
if (matchingNodes.includes(descendant)) {
return true;
}
}
return false;
}
showError(message) {
const errorDiv = document.getElementById('errorMessage');
errorDiv.textContent = this.sanitizeText(message);
errorDiv.style.display = 'block';
}
hideError() {
const errorDiv = document.getElementById('errorMessage');
errorDiv.style.display = 'none';
}
handleSearch() {
const searchInput = document.getElementById('searchInput');
const searchFilter = document.getElementById('searchFilter');
const query = searchInput.value.toLowerCase().trim();
const filterType = searchFilter.value;
this.performSearch(query, filterType);
}
clearSearch() {
const searchInput = document.getElementById('searchInput');
const searchFilter = document.getElementById('searchFilter');
searchInput.value = '';
searchFilter.value = 'all';
this.performSearch('', 'all');
}
collapseToFirstLevel() {
const tabContent = document.getElementById('tabContent');
if (!tabContent) return;
// Find all tree nodes with children
const allTreeNodes = tabContent.querySelectorAll('.tree-node');
allTreeNodes.forEach(node => {
const propertyChildren = node.querySelector('.property-children');
const expandIcon = node.querySelector('.expand-icon');
if (propertyChildren) {
// Check if this is a first-level property (direct child of spec)
const isFirstLevel = this.isFirstLevelProperty(node);
if (isFirstLevel) {
// Keep first level expanded
if (!propertyChildren.classList.contains('expanded')) {
propertyChildren.classList.add('expanded');
if (expandIcon) {
expandIcon.classList.add('expanded');
}
}
} else {
// Collapse everything else
if (propertyChildren.classList.contains('expanded')) {
propertyChildren.classList.remove('expanded');
if (expandIcon) {
expandIcon.classList.remove('expanded');
}
}
}
}
});
}
isFirstLevelProperty(node) {
// Walk up the tree to find the path
let current = node;
let depth = 0;
while (current && current.classList.contains('tree-node')) {
depth++;
// Look for the parent tree-node
current = current.parentElement;
if (current && current.classList.contains('property-children')) {
current = current.closest('.tree-node');
} else {
break;
}
}
// Top level properties should be at depth 1 (direct children of the root spec)
// The spec itself is considered depth 0, so its immediate children are depth 1
return depth <= 1;
}
formatPathForDisplay(fullPath) {
// Always show full path, but truncate from beginning if too long
const maxLength = 80; // Much larger limit since we have more space now
if (fullPath.length <= maxLength) {
return fullPath;
}
// Truncate from the beginning, keeping the end (most important part)
return '...' + fullPath.substring(fullPath.length - maxLength + 3);
}
toggleUploadSection() {
const uploadWrapper = document.getElementById('uploadWrapper');
const toggleButton = document.getElementById('toggleUpload');
if (uploadWrapper.classList.contains('hidden')) {
uploadWrapper.classList.remove('hidden');
toggleButton.textContent = '- Hide Upload';
} else {
uploadWrapper.classList.add('hidden');
toggleButton.textContent = '+ Upload More Files';
}
}
reapplySearch() {
const searchInput = document.getElementById('searchInput');
const searchFilter = document.getElementById('searchFilter');
if (searchInput && searchInput.value.trim()) {
const query = searchInput.value.toLowerCase().trim();
const filterType = searchFilter.value;
this.performSearch(query, filterType);
}
}
performSearch(query, filterType) {
const tabContent = document.getElementById('tabContent');
if (!tabContent) return;
// Clear all previous search highlighting and visibility
this.clearSearchHighlights(tabContent);
if (!query) {
// Show all nodes when search is empty
this.showAllNodes(tabContent);
return;
}
// Find all matching nodes
const matchingNodes = this.findMatchingNodes(tabContent, query, filterType);
// Hide all nodes first
this.hideAllNodes(tabContent);
// Show matching nodes and their parents
this.showMatchingNodesAndParents(matchingNodes);
// Highlight search matches
this.highlightSearchMatches(matchingNodes, query, filterType);
}
clearSearchHighlights(container) {
// Remove search highlighting
const highlightedElements = container.querySelectorAll('.search-highlight');
highlightedElements.forEach(element => {
const parent = element.parentNode;
parent.replaceChild(document.createTextNode(element.textContent), element);
parent.normalize();
});
// Remove search classes
const allNodes = container.querySelectorAll('.tree-node');
allNodes.forEach(node => {
node.classList.remove('search-hidden', 'search-match');
});
}
showAllNodes(container) {
const allNodes = container.querySelectorAll('.tree-node');
allNodes.forEach(node => {
node.classList.remove('search-hidden', 'search-match');
});
}
hideAllNodes(container) {
const allNodes = container.querySelectorAll('.tree-node');
allNodes.forEach(node => {
node.classList.add('search-hidden');
});
}
findMatchingNodes(container, query, filterType) {
const matchingNodes = [];
const allNodes = container.querySelectorAll('.tree-node');
allNodes.forEach(node => {
let isMatch = false;
if (filterType === 'all' || filterType === 'properties') {
// Search in property names
const propertyName = node.querySelector('.property-name');
if (propertyName && propertyName.textContent.toLowerCase().includes(query)) {
isMatch = true;
}
// Search in property paths
const propertyPath = node.querySelector('.property-path');
if (propertyPath && propertyPath.textContent.toLowerCase().includes(query)) {
isMatch = true;
}
}
if (filterType === 'all' || filterType === 'documentation') {
// Search in descriptions
const description = node.querySelector('.property-description');
if (description && description.textContent.toLowerCase().includes(query)) {
isMatch = true;
}
// Search in detail values
const detailValues = node.querySelectorAll('.detail-value');
detailValues.forEach(detail => {
if (detail.textContent.toLowerCase().includes(query)) {
isMatch = true;
}
});
}
if (isMatch) {
matchingNodes.push(node);
}
});
return matchingNodes;
}
showMatchingNodesAndParents(matchingNodes) {
// First, collapse all nodes that don't have search results
this.collapseNodesWithoutMatches(matchingNodes);
matchingNodes.forEach(node => {
// Show the matching node
node.classList.remove('search-hidden');
node.classList.add('search-match');
// Show all parent nodes
let parent = node.parentElement;
while (parent) {
if (parent.classList.contains('tree-node')) {
parent.classList.remove('search-hidden');
// Auto-expand parent nodes to show matched children
const propertyChildren = parent.querySelector('.property-children');
const expandIcon = parent.querySelector('.expand-icon');
if (propertyChildren && !propertyChildren.classList.contains('expanded')) {
propertyChildren.classList.add('expanded');
if (expandIcon) {
expandIcon.classList.add('expanded');
}
}
}
parent = parent.parentElement;
}
// Show all child nodes of matching nodes
const childNodes = node.querySelectorAll('.tree-node');
childNodes.forEach(child => {
child.classList.remove('search-hidden');
});
});
// Also show children of any manually expanded nodes during search
this.showManuallyExpandedNodes();
}
highlightSearchMatches(matchingNodes, query, filterType) {
matchingNodes.forEach(node => {
if (filterType === 'all' || filterType === 'properties') {
// Highlight in property names
const propertyName = node.querySelector('.property-name');
if (propertyName) {
this.highlightTextInElement(propertyName, query);
}
// Highlight in property paths
const propertyPath = node.querySelector('.property-path');
if (propertyPath) {
this.highlightTextInElement(propertyPath, query);
}
}
if (filterType === 'all' || filterType === 'documentation') {
// Highlight in descriptions
const description = node.querySelector('.property-description');
if (description) {
this.highlightTextInElement(description, query);
}
// Highlight in detail values
const detailValues = node.querySelectorAll('.detail-value');
detailValues.forEach(detail => {
this.highlightTextInElement(detail, query);
});
}
});
}
highlightTextInElement(element, query) {
const text = element.textContent;
const lowerText = text.toLowerCase();
const lowerQuery = query.toLowerCase();
if (!lowerText.includes(lowerQuery)) return;
const parts = [];
let lastIndex = 0;
let index = lowerText.indexOf(lowerQuery);
while (index !== -1) {
// Add text before match
if (index > lastIndex) {
parts.push(document.createTextNode(text.substring(lastIndex, index)));
}
// Add highlighted match - use the original text case and proper length
const highlight = document.createElement('span');
highlight.className = 'search-highlight';
highlight.textContent = text.substring(index, index + lowerQuery.length);
parts.push(highlight);
lastIndex = index + lowerQuery.length;
index = lowerText.indexOf(lowerQuery, lastIndex);
}
// Add remaining text
if (lastIndex < text.length) {
parts.push(document.createTextNode(text.substring(lastIndex)));
}
// Replace element content