-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree_report.py
More file actions
1094 lines (999 loc) · 33.1 KB
/
Copy pathtree_report.py
File metadata and controls
1094 lines (999 loc) · 33.1 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
"""Generate a static left-to-right file tree from scan-result.json."""
from __future__ import annotations
import html
import json
import os
from collections import Counter
from pathlib import Path
from typing import Any
from urllib.parse import quote
PROJECT_DIR = Path(__file__).resolve().parent
INPUT_PATH = PROJECT_DIR / "outputs" / "scan-result.json"
OUTPUT_PATH = PROJECT_DIR / "outputs" / "tree.html"
MAX_PRIMARY_FILE_TYPES = 6
FOLDER_ICON = "📁"
DEFAULT_FILE_ICON = "📄"
FILE_ICONS = {
".py": "🐍",
".md": "📓",
".txt": "📝",
".pdf": "📕",
".doc": "📘",
".docx": "📘",
".xls": "📊",
".xlsx": "📊",
".csv": "📊",
".png": "🖼️",
".jpg": "🖼️",
".jpeg": "🖼️",
".gif": "🖼️",
".webp": "🖼️",
".mp4": "🎬",
".mkv": "🎬",
".avi": "🎬",
".mov": "🎬",
".mp3": "🎵",
".wav": "🎵",
".flac": "🎵",
".zip": "🗜️",
".rar": "🗜️",
".7z": "🗜️",
".html": "🌐",
".htm": "🌐",
".css": "🎨",
".js": "📜",
".ts": "📜",
".json": "🧩",
".yaml": "🧩",
".yml": "🧩",
".toml": "🧩",
}
def load_scan_result(path: Path = INPUT_PATH) -> dict[str, Any]:
"""Load and minimally validate a scan result JSON file."""
with path.open("r", encoding="utf-8") as input_file:
data = json.load(input_file)
if not isinstance(data, dict) or not isinstance(data.get("root"), dict):
raise ValueError("JSON 中缺少有效的 root 节点")
return data
def _select_icon(node: dict[str, Any]) -> str:
if node.get("type") == "directory":
return FOLDER_ICON
extension = Path(str(node.get("name", ""))).suffix.casefold()
return FILE_ICONS.get(extension, DEFAULT_FILE_ICON)
def _format_size(size: int) -> str:
units = ("B", "KB", "MB", "GB", "TB")
value = float(size)
for unit in units:
if value < 1024 or unit == units[-1]:
return f"{int(value)} {unit}" if unit == "B" else f"{value:.2f} {unit}"
value /= 1024
return f"{size} B"
def _summary_number(data: dict[str, Any], key: str) -> int:
value = data.get(key, 0)
return value if isinstance(value, int) and not isinstance(value, bool) else 0
def _collect_extension_counts(root: dict[str, Any]) -> Counter[str]:
counts: Counter[str] = Counter()
pending = [root]
while pending:
node = pending.pop()
if node.get("type") == "file":
extension = Path(str(node.get("name", ""))).suffix.casefold()
counts[extension] += 1
children = node.get("children", [])
if isinstance(children, list):
pending.extend(child for child in children if isinstance(child, dict))
return counts
def _render_statistics(data: dict[str, Any]) -> str:
extension_counts = _collect_extension_counts(data["root"])
ranked_types = sorted(
extension_counts.items(), key=lambda item: (-item[1], item[0])
)
primary_types = ranked_types[:MAX_PRIMARY_FILE_TYPES]
other_count = sum(count for _, count in ranked_types[MAX_PRIMARY_FILE_TYPES:])
type_items = []
for extension, count in primary_types:
label = extension or "无扩展名"
icon = FILE_ICONS.get(extension, DEFAULT_FILE_ICON)
type_items.append(
'<span class="type-item">'
f'<span aria-hidden="true">{icon}</span>'
f'<span>{html.escape(label)}</span>'
f"<strong>{count:,}</strong>"
"</span>"
)
if other_count:
type_items.append(
'<span class="type-item">'
'<span aria-hidden="true">📦</span>'
"<span>其他</span>"
f"<strong>{other_count:,}</strong>"
"</span>"
)
if not type_items:
type_items.append('<span class="type-empty">没有文件</span>')
directory_count = _summary_number(data, "directory_count")
file_count = _summary_number(data, "file_count")
total_size = _summary_number(data, "total_size")
return (
'<section class="directory-statistics" aria-label="目录统计">'
'<div class="stat-item"><span>文件夹数量</span>'
f"<strong>{directory_count:,}</strong></div>"
'<div class="stat-item"><span>文件数量</span>'
f"<strong>{file_count:,}</strong></div>"
'<div class="stat-item"><span>总大小</span>'
f'<strong title="{total_size:,} 字节">{_format_size(total_size)}</strong></div>'
'<div class="type-statistics"><span class="type-label">主要文件类型</span>'
f'<div class="type-list">{"".join(type_items)}</div></div>'
"</section>"
)
def _prepare_tree(node: dict[str, Any]) -> dict[str, Any]:
children = node.get("children", [])
prepared_children = (
[_prepare_tree(child) for child in children if isinstance(child, dict)]
if isinstance(children, list)
else []
)
return {
"name": str(node.get("name", "未命名")),
"path": str(node.get("path", "")),
"type": "directory" if node.get("type") == "directory" else "file",
"icon": _select_icon(node),
"children": prepared_children,
}
def _serialize_tree(node: dict[str, Any]) -> str:
tree_json = json.dumps(
_prepare_tree(node), ensure_ascii=False, separators=(",", ":")
)
return (
tree_json.replace("&", "\\u0026")
.replace("<", "\\u003c")
.replace(">", "\\u003e")
.replace("\u2028", "\\u2028")
.replace("\u2029", "\\u2029")
)
def _render_svg_export_button(
svg_export_path: Path | None,
html_output_path: Path,
) -> str:
"""Return a safe relative download link for an existing SVG export."""
if svg_export_path is None:
return ""
svg_path = Path(svg_export_path).resolve()
if not svg_path.is_file():
return ""
try:
relative_path = os.path.relpath(
svg_path, start=Path(html_output_path).resolve().parent
)
except ValueError:
return ""
href = quote(Path(relative_path).as_posix(), safe="/")
return (
'<a class="toolbar-button export-button" '
f'href="{html.escape(href, quote=True)}" '
f'download="{html.escape(svg_path.name, quote=True)}" '
'title="下载独立 SVG 文件树">导出 SVG</a>'
)
def generate_html(
data: dict[str, Any],
svg_export_path: Path | None = None,
html_output_path: Path = OUTPUT_PATH,
) -> str:
"""Build a standalone left-to-right file tree from scan result data."""
root = data["root"]
tree_json = _serialize_tree(root)
scan_path = html.escape(str(root.get("path", "")), quote=True)
statistics_html = _render_statistics(data)
svg_export_button = _render_svg_export_button(
svg_export_path, html_output_path
)
return (
"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FolderVisualizer 横向文件树</title>
<style>
:root {
color-scheme: light;
font-family: "Segoe UI", "Microsoft YaHei", sans-serif;
color: #182033;
background: #f4f7fb;
}
* { box-sizing: border-box; }
body { margin: 0; background: #f4f7fb; }
main { width: min(1600px, calc(100% - 32px)); margin: 28px auto; }
header { margin-bottom: 16px; }
h1 { margin: 0 0 8px; font-size: 28px; font-weight: 650; }
.scan-path { margin: 0; color: #667085; overflow-wrap: anywhere; }
.directory-statistics {
display: grid;
grid-template-columns: 150px 150px 180px minmax(320px, 1fr);
gap: 10px;
margin-bottom: 12px;
padding: 12px;
border: 1px solid #dfe6ef;
border-radius: 10px;
background: #ffffff;
}
.stat-item {
display: flex;
flex-direction: column;
justify-content: center;
gap: 3px;
padding: 5px 8px;
color: #667085;
}
.stat-item strong { color: #182033; font-size: 20px; }
.type-statistics {
display: flex;
align-items: center;
gap: 10px;
min-width: 0;
padding: 5px 8px;
border-left: 1px solid #e5eaf1;
}
.type-label { flex: 0 0 auto; color: #667085; }
.type-list { display: flex; flex-wrap: wrap; gap: 6px; min-width: 0; }
.type-item {
display: inline-flex;
align-items: center;
gap: 5px;
padding: 4px 7px;
border-radius: 6px;
background: #f3f6fa;
color: #475467;
white-space: nowrap;
}
.type-item strong { color: #182033; }
.type-empty { color: #98a2b3; }
.tree-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 12px;
}
.search-toolbar {
display: flex;
align-items: center;
gap: 10px;
min-width: 0;
flex: 1 1 620px;
}
.search-label { flex: 0 0 auto; font-weight: 600; }
.search-input {
min-width: 180px;
flex: 1 1 360px;
height: 38px;
padding: 7px 11px;
border: 1px solid #cfd8e5;
border-radius: 8px;
background: #ffffff;
color: #182033;
font: inherit;
}
.search-input:focus {
border-color: #6f9fd5;
outline: 2px solid #d9e9fb;
outline-offset: 1px;
}
.toolbar-button {
display: inline-flex;
align-items: center;
justify-content: center;
height: 38px;
padding: 0 14px;
border: 1px solid #cfd8e5;
border-radius: 8px;
background: #ffffff;
color: #344054;
font: inherit;
line-height: 1;
text-decoration: none;
white-space: nowrap;
cursor: pointer;
}
.toolbar-button:hover:not(:disabled) { background: #f3f7fc; }
.toolbar-button:disabled { color: #98a2b3; cursor: default; }
.search-count {
min-width: 104px;
color: #667085;
text-align: right;
white-space: nowrap;
}
.map-actions {
display: flex;
align-items: center;
gap: 8px;
flex: 0 0 auto;
}
.zoom-controls {
display: inline-flex;
align-items: center;
gap: 6px;
}
.zoom-button { min-width: 62px; padding: 0 10px; }
.zoom-level {
min-width: 58px;
color: #475467;
text-align: center;
white-space: nowrap;
}
.fit-button.active {
border-color: #6f9fd5;
background: #eaf3fd;
color: #164a84;
}
.export-button {
border-color: #4d87c5;
background: #e7f1ff;
color: #164a84;
font-weight: 600;
}
.export-button:hover { background: #d9eaff; }
.map-viewport {
height: clamp(520px, calc(100vh - 295px), 820px);
overflow: auto;
background: #ffffff;
border: 1px solid #dfe6ef;
border-radius: 12px;
box-shadow: 0 7px 24px rgba(35, 52, 78, 0.06);
}
.map-canvas {
position: relative;
min-width: 100%;
min-height: 100%;
}
.map-scene {
position: absolute;
left: 0;
top: 0;
transform: scale(1);
transform-origin: 0 0;
}
.connectors {
position: absolute;
inset: 0;
overflow: visible;
pointer-events: none;
}
.connector {
fill: none;
stroke: #c3ccd8;
stroke-width: 1;
stroke-linecap: round;
stroke-linejoin: round;
}
.nodes { position: absolute; inset: 0; }
.map-node {
position: absolute;
z-index: 2;
display: flex;
align-items: center;
gap: 8px;
width: 240px;
height: 40px;
padding: 7px 11px;
border: 1px solid #dce3ec;
border-radius: 8px;
background: #ffffff;
color: #344054;
box-shadow: 0 2px 7px rgba(35, 52, 78, 0.05);
}
.map-node.directory {
border-color: #cbdcf3;
background: #f3f8ff;
color: #164a84;
font-weight: 600;
}
.map-node.file { cursor: pointer; }
.map-node.file:focus-visible {
outline: 2px solid #6f9fd5;
outline-offset: 2px;
}
.map-node.file.name-expanded {
z-index: 4;
width: max-content;
min-width: 240px;
max-width: 560px;
height: auto;
min-height: 40px;
align-items: flex-start;
}
.map-node.file.name-expanded .name {
overflow: visible;
text-overflow: clip;
white-space: normal;
overflow-wrap: anywhere;
}
.map-node.root {
border-color: #84aee0;
background: #e7f1ff;
box-shadow: 0 4px 13px rgba(35, 85, 145, 0.14);
}
.map-node.search-match {
outline: 2px solid #e9b949;
outline-offset: 2px;
background: #fff8d9;
}
.map-node.search-active {
z-index: 3;
outline: 3px solid #df7b24;
outline-offset: 3px;
background: #fff0d9;
}
.icon { flex: 0 0 auto; line-height: 1; }
.name {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.name.file-name {
display: flex;
max-width: 100%;
text-overflow: clip;
}
.file-name-prefix {
min-width: 0;
flex: 0 1 auto;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.file-name-suffix {
flex: 0 0 auto;
white-space: nowrap;
}
.name.file-name-full { display: block; }
noscript { display: block; padding: 24px; color: #9b2c2c; }
@media (max-width: 600px) {
main { width: min(100% - 20px, 1600px); margin-top: 18px; }
h1 { font-size: 24px; }
.directory-statistics { grid-template-columns: repeat(3, minmax(0, 1fr)); }
.stat-item { padding: 3px; }
.stat-item strong { font-size: 17px; }
.type-statistics {
grid-column: 1 / -1;
align-items: flex-start;
border-top: 1px solid #e5eaf1;
border-left: 0;
padding: 9px 3px 3px;
}
.tree-toolbar { align-items: stretch; flex-direction: column; }
.search-toolbar { flex: 0 1 auto; flex-wrap: wrap; }
.search-label { width: 100%; }
.search-count { min-width: 86px; }
.map-actions { flex-wrap: wrap; }
.map-viewport { height: calc(100vh - 300px); min-height: 440px; }
}
</style>
</head>
<body>
<main>
<header>
<h1>横向文件结构树</h1>
<p class="scan-path">"""
+ scan_path
+ """</p>
</header>
"""
+ statistics_html
+ """
<div class="tree-toolbar">
<div class="search-toolbar" role="search">
<label class="search-label" for="tree-search">搜索节点</label>
<input
id="tree-search"
class="search-input"
type="search"
placeholder="输入文件名或目录名"
autocomplete="off"
>
<button id="search-previous" class="toolbar-button" type="button" disabled>上一个</button>
<button id="search-next" class="toolbar-button" type="button" disabled>下一个</button>
<output id="search-count" class="search-count" aria-live="polite">0 个匹配</output>
</div>
<div class="map-actions" aria-label="文件树视图操作">
<div class="zoom-controls" aria-label="缩放控制" title="按住 Ctrl 并滚动鼠标滚轮也可缩放">
<button id="zoom-out" class="toolbar-button zoom-button" type="button" title="缩小文件树">缩小</button>
<output id="zoom-level" class="zoom-level" aria-live="polite">100%</output>
<button id="zoom-in" class="toolbar-button zoom-button" type="button" title="放大文件树">放大</button>
<button id="zoom-reset" class="toolbar-button zoom-button" type="button" title="恢复到 100%">100%</button>
<button id="zoom-fit" class="toolbar-button zoom-button fit-button" type="button" aria-pressed="false" title="让完整文件树适应当前窗口">适应窗口</button>
</div>
"""
+ svg_export_button
+ """
</div>
</div>
<div id="map-viewport" class="map-viewport" aria-label="从左向右展开的完整文件结构树">
<div id="map-canvas" class="map-canvas">
<div id="map-scene" class="map-scene">
<svg id="connectors" class="connectors" aria-hidden="true"></svg>
<div id="nodes" class="nodes"></div>
</div>
</div>
<noscript>此文件地图需要启用 JavaScript 才能计算节点位置。</noscript>
</div>
</main>
<script>
"use strict";
const treeData = """
+ tree_json
+ """;
const NODE_WIDTH = 240;
const NODE_HEIGHT = 40;
const COLUMN_GAP = 96;
const DEPTH_STEP = NODE_WIDTH + COLUMN_GAP;
const ROW_GAP = 52;
const CANVAS_PADDING = 40;
const SVG_NS = "http://www.w3.org/2000/svg";
const MIN_MANUAL_SCALE = 0.25;
const MAX_MANUAL_SCALE = 2.5;
const ZOOM_STEP = 0.25;
const MIN_FIT_SCALE = 0.01;
const viewport = document.getElementById("map-viewport");
const canvas = document.getElementById("map-canvas");
const scene = document.getElementById("map-scene");
const connectorLayer = document.getElementById("connectors");
const nodesLayer = document.getElementById("nodes");
const searchInput = document.getElementById("tree-search");
const previousButton = document.getElementById("search-previous");
const nextButton = document.getElementById("search-next");
const searchCount = document.getElementById("search-count");
const zoomOutButton = document.getElementById("zoom-out");
const zoomInButton = document.getElementById("zoom-in");
const zoomResetButton = document.getElementById("zoom-reset");
const zoomFitButton = document.getElementById("zoom-fit");
const zoomLevel = document.getElementById("zoom-level");
let searchableNodes = [];
let searchMatches = [];
let activeMatchIndex = -1;
let currentScale = 1;
let fitMode = false;
let logicalCanvasWidth = 0;
let logicalCanvasHeight = 0;
const expandedFilePaths = new Set();
function normalizeNode(node) {
const children = Array.isArray(node.children)
? node.children.map(normalizeNode)
: [];
return {
name: String(node.name ?? "未命名"),
path: String(node.path ?? ""),
type: node.type === "directory" ? "directory" : "file",
icon: String(node.icon ?? "📄"),
children,
};
}
function layoutTree(root) {
const positions = [];
const branchGroups = [];
let nextLeafY = 0;
let maxDepth = 0;
let maxY = 0;
function visit(node, depth, parent) {
const position = {
node,
depth,
parent,
x: CANVAS_PADDING + depth * DEPTH_STEP,
y: 0,
};
positions.push(position);
maxDepth = Math.max(maxDepth, depth);
const childPositions = node.children.map((child) =>
visit(child, depth + 1, position)
);
if (childPositions.length === 0) {
position.y = nextLeafY;
nextLeafY += ROW_GAP;
} else {
position.y = (
childPositions[0].y + childPositions[childPositions.length - 1].y
) / 2;
branchGroups.push({ parent: position, children: childPositions });
}
maxY = Math.max(maxY, position.y);
return position;
}
const rootPosition = visit(root, 0, null);
return { positions, branchGroups, rootPosition, maxDepth, maxY };
}
function renderNameContent(name, node, showFullName = false) {
name.replaceChildren();
name.className = "name";
if (node.type === "directory" || showFullName) {
if (showFullName) {
name.className = "name file-name-full";
}
name.textContent = node.name;
return;
}
const extensionStart = node.name.lastIndexOf(".");
if (extensionStart <= 0 || extensionStart === node.name.length - 1) {
name.textContent = node.name;
return;
}
const stem = node.name.slice(0, extensionStart);
const extension = node.name.slice(extensionStart);
const suffixStart = Math.max(0, stem.length - 5);
const prefixText = stem.slice(0, suffixStart);
const suffixText = stem.slice(suffixStart) + extension;
if (!prefixText) {
name.textContent = suffixText;
return;
}
name.className = "name file-name";
const prefix = document.createElement("span");
prefix.className = "file-name-prefix";
prefix.textContent = prefixText;
const suffix = document.createElement("span");
suffix.className = "file-name-suffix";
suffix.textContent = suffixText;
name.append(prefix, suffix);
}
function createNameElement(node, showFullName = false) {
const name = document.createElement("span");
renderNameContent(name, node, showFullName);
return name;
}
function setFileNameExpanded(element, name, node, expanded) {
element.classList[expanded ? "add" : "remove"]("name-expanded");
element.setAttribute("aria-expanded", String(expanded));
if (expanded) {
expandedFilePaths.add(node.path);
} else {
expandedFilePaths.delete(node.path);
}
renderNameContent(name, node, expanded);
}
function createNode(position, isRoot = false) {
const element = document.createElement("div");
element.className = `map-node ${position.node.type}${isRoot ? " root" : ""}`;
element.style.left = `${position.x}px`;
element.style.top = `${position.y - NODE_HEIGHT / 2}px`;
element.title = `${position.node.name}\n${position.node.path}`;
element.setAttribute("data-depth", String(position.depth));
element.setAttribute(
"aria-label",
`${position.node.type === "directory" ? "目录" : "文件"}:${position.node.name}`
);
const icon = document.createElement("span");
icon.className = "icon";
icon.setAttribute("aria-hidden", "true");
icon.textContent = position.node.icon;
const isExpanded = (
position.node.type === "file" && expandedFilePaths.has(position.node.path)
);
const name = createNameElement(position.node, isExpanded);
element.append(icon, name);
if (position.node.type === "file") {
element.setAttribute("role", "button");
element.setAttribute("tabindex", "0");
element.setAttribute("aria-expanded", String(isExpanded));
if (isExpanded) {
element.classList.add("name-expanded");
}
element.addEventListener("click", () =>
setFileNameExpanded(
element,
name,
position.node,
!element.classList.contains("name-expanded")
)
);
element.addEventListener("keydown", (event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
setFileNameExpanded(
element,
name,
position.node,
!element.classList.contains("name-expanded")
);
}
});
}
nodesLayer.appendChild(element);
searchableNodes.push({
element,
position,
normalizedName: position.node.name.toLocaleLowerCase(),
});
}
function clamp(value, minimum, maximum) {
return Math.min(maximum, Math.max(minimum, value));
}
function updateZoomControls() {
zoomLevel.textContent = `${Math.round(currentScale * 100)}%`;
zoomOutButton.disabled = currentScale <= MIN_MANUAL_SCALE + 0.0001;
zoomInButton.disabled = currentScale >= MAX_MANUAL_SCALE - 0.0001;
zoomFitButton.classList.toggle("active", fitMode);
zoomFitButton.setAttribute("aria-pressed", String(fitMode));
}
function updateSceneDimensions() {
scene.style.width = `${logicalCanvasWidth}px`;
scene.style.height = `${logicalCanvasHeight}px`;
scene.style.transform = `scale(${currentScale})`;
const scaledWidth = Math.ceil(logicalCanvasWidth * currentScale);
const scaledHeight = Math.ceil(logicalCanvasHeight * currentScale);
canvas.style.width = `${Math.max(viewport.clientWidth, scaledWidth)}px`;
canvas.style.height = `${Math.max(viewport.clientHeight, scaledHeight)}px`;
updateZoomControls();
}
function applyScale(
nextScale,
anchorX = viewport.clientWidth / 2,
anchorY = viewport.clientHeight / 2,
preserveFitMode = false
) {
if (logicalCanvasWidth <= 0 || logicalCanvasHeight <= 0) {
return;
}
const previousScale = currentScale;
const logicalAnchorX = (viewport.scrollLeft + anchorX) / previousScale;
const logicalAnchorY = (viewport.scrollTop + anchorY) / previousScale;
currentScale = nextScale;
if (!preserveFitMode) {
fitMode = false;
}
updateSceneDimensions();
viewport.scrollLeft = Math.max(
0, logicalAnchorX * currentScale - anchorX
);
viewport.scrollTop = Math.max(
0, logicalAnchorY * currentScale - anchorY
);
}
function applyManualScale(
requestedScale,
anchorX = viewport.clientWidth / 2,
anchorY = viewport.clientHeight / 2
) {
applyScale(
clamp(requestedScale, MIN_MANUAL_SCALE, MAX_MANUAL_SCALE),
anchorX,
anchorY
);
}
function zoomByStep(direction) {
if (currentScale < MIN_MANUAL_SCALE) {
if (direction > 0) {
applyManualScale(MIN_MANUAL_SCALE);
}
return;
}
applyManualScale(currentScale + direction * ZOOM_STEP);
}
function fitTreeToViewport() {
if (logicalCanvasWidth <= 0 || logicalCanvasHeight <= 0) {
return;
}
const availableWidth = Math.max(1, viewport.clientWidth - 16);
const availableHeight = Math.max(1, viewport.clientHeight - 16);
const fitScale = clamp(
Math.min(
1,
availableWidth / logicalCanvasWidth,
availableHeight / logicalCanvasHeight
),
MIN_FIT_SCALE,
1
);
fitMode = true;
applyScale(fitScale, 0, 0, true);
viewport.scrollLeft = 0;
viewport.scrollTop = 0;
}
function updateSearchControls() {
const matchCount = searchMatches.length;
searchCount.textContent = matchCount > 0
? `${activeMatchIndex + 1} / ${matchCount} 个匹配`
: "0 个匹配";
previousButton.disabled = matchCount <= 1;
nextButton.disabled = matchCount <= 1;
}
function scrollToMatch(match) {
viewport.scrollLeft = Math.max(
0,
(match.position.x + NODE_WIDTH / 2) * currentScale
- viewport.clientWidth / 2
);
viewport.scrollTop = Math.max(
0,
match.position.y * currentScale - viewport.clientHeight / 2
);
}
function selectMatch(index, shouldScroll = true) {
searchMatches.forEach((match) =>
match.element.classList.remove("search-active")
);
if (searchMatches.length === 0) {
activeMatchIndex = -1;
updateSearchControls();
return;
}
activeMatchIndex = (
(index % searchMatches.length) + searchMatches.length
) % searchMatches.length;
const activeMatch = searchMatches[activeMatchIndex];
activeMatch.element.classList.add("search-active");
updateSearchControls();
if (shouldScroll) {
scrollToMatch(activeMatch);
}
}
function runSearch(resetIndex = true, shouldScroll = true) {
const query = searchInput.value.trim().toLocaleLowerCase();
searchableNodes.forEach((item) =>
item.element.classList.remove("search-match", "search-active")
);
searchMatches = [];
if (!query) {
activeMatchIndex = -1;
updateSearchControls();
return;
}
searchMatches = searchableNodes.filter((item) =>
item.normalizedName.includes(query)
);
searchMatches.forEach((match) =>
match.element.classList.add("search-match")
);
if (searchMatches.length === 0) {
activeMatchIndex = -1;
updateSearchControls();
return;
}
const nextIndex = resetIndex
? 0
: Math.min(Math.max(activeMatchIndex, 0), searchMatches.length - 1);
selectMatch(nextIndex, shouldScroll);
}
function drawBranch(group) {
const startX = group.parent.x + NODE_WIDTH;
const branchX = startX + COLUMN_GAP / 2;
const firstChild = group.children[0];
const lastChild = group.children[group.children.length - 1];
const commands = [];
if (group.children.length === 1) {
commands.push(`M ${startX} ${group.parent.y} H ${firstChild.x}`);
} else {
commands.push(`M ${startX} ${group.parent.y} H ${branchX}`);
commands.push(`M ${branchX} ${firstChild.y} V ${lastChild.y}`);
group.children.forEach((child) => {
commands.push(`M ${branchX} ${child.y} H ${child.x}`);
});
}
const path = document.createElementNS(SVG_NS, "path");
path.setAttribute("class", "connector");
path.setAttribute("d", commands.join(" "));
connectorLayer.appendChild(path);
}
function renderMap() {
connectorLayer.replaceChildren();
nodesLayer.replaceChildren();
searchableNodes = [];
const layout = layoutTree(normalizeNode(treeData));
const requiredWidth = (
CANVAS_PADDING * 2
+ (layout.maxDepth + 1) * NODE_WIDTH
+ layout.maxDepth * COLUMN_GAP
);
logicalCanvasWidth = requiredWidth;
logicalCanvasHeight = Math.max(
layout.maxY + NODE_HEIGHT + CANVAS_PADDING * 2,
520
);
const yOffset = CANVAS_PADDING + NODE_HEIGHT / 2;
connectorLayer.setAttribute(
"viewBox", `0 0 ${logicalCanvasWidth} ${logicalCanvasHeight}`
);
connectorLayer.setAttribute("width", String(logicalCanvasWidth));
connectorLayer.setAttribute("height", String(logicalCanvasHeight));
layout.positions.forEach((position) => { position.y += yOffset; });
layout.branchGroups.forEach(drawBranch);
layout.positions.forEach((position) =>
createNode(position, position === layout.rootPosition)
);
updateSceneDimensions();
viewport.scrollLeft = 0;
viewport.scrollTop = Math.max(
0,
layout.rootPosition.y * currentScale - viewport.clientHeight / 2
);
runSearch(false, Boolean(searchInput.value.trim()));
}
searchInput.addEventListener("input", () => runSearch(true, true));
searchInput.addEventListener("keydown", (event) => {
if (event.key === "Enter" && searchMatches.length > 0) {
event.preventDefault();
selectMatch(activeMatchIndex + (event.shiftKey ? -1 : 1), true);