-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathwebhelpsearch.htm
More file actions
1283 lines (1135 loc) · 38 KB
/
Copy pathwebhelpsearch.htm
File metadata and controls
1283 lines (1135 loc) · 38 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
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head><meta charset="utf-8">
<title>搜索</title>
<style>
* {
box-sizing: border-box;
}
html, body {
height: 100%;
}
body {
margin: 0;
padding: 12px 12px 16px;
font-family: "Microsoft YaHei", "Inter", sans-serif;
background: transparent;
color: #0f172a;
overflow-y: auto;
}
.search-container {
background: #ffffff;
border: 1px solid #e2e8f0;
border-radius: 12px;
padding: 16px;
box-shadow: 0 6px 16px rgba(15, 23, 42, 0.08);
}
.search-title {
font-size: 1.1rem;
font-weight: 600;
color: #0f172a;
margin-bottom: 12px;
}
.search-input-wrapper {
position: relative;
}
#keyword {
width: 100%;
padding: 10px 12px;
border: 1px solid #cbd5f5;
border-radius: 10px;
font-size: 14px;
background: #f8fafc;
transition: all 0.2s ease;
}
#keyword:focus {
border-color: #2563eb;
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.18);
background: #ffffff;
outline: none;
}
.search-help-bubble {
position: absolute;
top: calc(100% + 6px);
left: 0;
max-width: 360px;
padding: 10px 12px;
font-size: 12px;
line-height: 1.6;
color: #334155;
background: #f8fafc;
border: 1px solid #cbd5f5;
border-radius: 10px;
box-shadow: 0 6px 18px rgba(15, 23, 42, 0.12);
opacity: 0;
pointer-events: none;
transform: translateY(-4px);
transition: opacity 0.18s ease, transform 0.18s ease;
z-index: 20;
}
.search-help-bubble strong {
color: #1d4ed8;
}
.search-help-bubble code {
background: #e0e7ff;
color: #1e3a8a;
border-radius: 4px;
padding: 1px 4px;
font-size: 11px;
}
.search-input-wrapper:hover .search-help-bubble,
.search-input-wrapper:focus-within .search-help-bubble {
opacity: 1;
transform: translateY(0);
}
.options-row {
display: flex;
align-items: center;
gap: 12px;
margin: 12px 0;
font-size: 12px;
color: #475569;
flex-wrap: wrap;
}
.checkbox-label {
display: inline-flex;
align-items: center;
gap: 6px;
cursor: pointer;
}
.checkbox-label input {
width: 14px;
height: 14px;
accent-color: #2563eb;
}
.filter-item {
display: inline-flex;
align-items: center;
gap: 6px;
}
.filter-label {
font-size: 12px;
color: #475569;
}
.filter-select {
min-width: 150px;
padding: 6px 10px;
border: 1px solid #cbd5f5;
border-radius: 10px;
background: #f8fafc;
font-size: 12px;
color: #1f2937;
}
.filter-select:focus {
outline: none;
border-color: #2563eb;
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.15);
background: #ffffff;
}
.btn-group {
display: flex;
gap: 10px;
}
.btn {
border: none;
border-radius: 8px;
padding: 8px 14px;
font-size: 12px;
font-weight: 600;
cursor: pointer;
transition: all 0.2s ease;
display: inline-flex;
align-items: center;
gap: 6px;
}
.btn-primary {
background: #2563eb;
color: #ffffff;
}
.btn-primary:hover {
background: #1d4ed8;
}
.btn-secondary {
background: #e0e7ff;
color: #1e3a8a;
}
.btn-secondary:hover {
background: #c7d2fe;
}
.btn-ghost {
background: transparent;
color: #2563eb;
}
.btn-ghost:hover {
background: rgba(37, 99, 235, 0.08);
}
.results-wrapper {
margin-top: 14px;
background: #ffffff;
border: 1px solid #e2e8f0;
border-radius: 12px;
padding: 14px;
box-shadow: 0 8px 20px rgba(15, 23, 42, 0.12);
}
.results-info {
display: none;
background: #eff6ff;
color: #1d4ed8;
font-size: 12px;
padding: 8px 10px;
border-radius: 8px;
margin-bottom: 10px;
}
.results-info strong {
font-weight: 700;
}
.results-list-container {
border: 1px solid #f1f5f9;
border-radius: 10px;
overflow: hidden;
}
.results-header {
display: grid;
grid-template-columns: 1.4fr 1fr;
background: #f8fafc;
padding: 10px 14px;
font-size: 12px;
font-weight: 600;
color: #64748b;
}
.results-list {
margin: 0;
padding: 0;
list-style: none;
max-height: 60vh;
overflow-y: auto;
}
.result-item {
display: grid;
grid-template-columns: 1.4fr 1fr;
gap: 12px;
align-items: center;
padding: 12px 14px;
font-size: 12px;
color: #1f2937;
border-bottom: 1px solid #f1f5f9;
cursor: pointer;
transition: background 0.15s ease;
}
.result-item:hover {
background: #eef2ff;
}
.result-item.selected {
background: #e0e7ff;
border-left: 3px solid #2563eb;
}
.result-main-title {
display: flex;
flex-direction: column;
gap: 4px;
}
.result-title-text {
font-weight: 600;
color: #111827;
line-height: 1.4;
}
.result-rank {
font-size: 11px;
font-weight: 500;
color: #1d4ed8;
background: rgba(37, 99, 235, 0.12);
padding: 2px 8px;
border-radius: 999px;
display: inline-flex;
width: fit-content;
}
.result-meta {
font-size: 12px;
color: #475569;
}
.empty-state {
list-style: none;
padding: 24px;
text-align: center;
color: #94a3b8;
font-size: 12px;
}
.empty-text {
line-height: 1.6;
}
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-thumb {
background: rgba(148, 163, 184, 0.6);
border-radius: 999px;
}
::-webkit-scrollbar-track {
background: transparent;
}
.preview-tooltip {
position: fixed;
top: -9999px;
left: -9999px;
max-width: 420px;
width: min(420px, 45vw);
background: #111827;
color: #f8fafc;
border-radius: 10px;
padding: 12px;
box-shadow: 0 12px 28px rgba(15, 23, 42, 0.3);
font-size: 12px;
line-height: 1.6;
z-index: 9999;
pointer-events: none;
opacity: 0;
transition: opacity 0.15s ease;
}
.preview-tooltip.visible {
opacity: 1;
}
.preview-tooltip__title {
font-weight: 600;
margin-bottom: 6px;
color: #cbd5f5;
}
.preview-tooltip__content {
max-height: 260px;
overflow-y: auto;
white-space: pre-wrap;
}
.preview-tooltip__content mark {
background: rgba(37, 99, 235, 0.6);
color: #ffffff;
border-radius: 4px;
padding: 0 2px;
}
.preview-tooltip__empty {
color: #94a3b8;
}
.server-error {
background: #fee2e2;
color: #991b1b;
border-radius: 10px;
padding: 14px;
margin: 16px;
border: 1px solid #fecaca;
font-size: 12px;
}
</style>
<script>
var words = [];
var lastResultIndexes = [];
var previewTooltip;
var previewTitleElem;
var previewContentElem;
var categorySelect;
var cachedCategories = [];
var API_BASE = "https://5echmsearch.kagangtuya.top"
var highlightRequestId = 0;
var pendingContentLoadCleanup;
function searchLog(message, detail) {
return;
}
function searchFrameContext() {
try {
return {
name: window.name || '',
href: window.location.href,
parentName: window.parent && window.parent.name || '',
topName: window.top && window.top.name || ''
};
} catch (e) {
return { error: String(e && e.message || e) };
}
}
function postSearchBridge(url, requestId) {
try {
var receiver = window.parent;
if (!receiver || !receiver.postMessage) return;
receiver.postMessage({
type: 'webhelp-search-navigate',
url: url,
words: words.slice(),
requestId: requestId
}, '*');
searchLog('bridge message sent', { requestId: requestId, url: url });
} catch (e) {
searchLog('bridge message failed', { requestId: requestId, error: String(e && e.message || e) });
}
}
function resolveContentUrl(url) {
try {
var link = document.createElement('a');
link.href = url;
return link.href;
} catch (e) {
return url;
}
}
if (window.addEventListener) {
window.addEventListener('message', function(event) {
var data = event && event.data;
if (data && data.type === 'webhelp-search-highlighted') {
searchLog('bridge highlight complete', data);
}
}, false);
searchLog('search bridge ready');
}
function extractHighlightTerms(input) {
if (!input) return [];
var terms = [];
var regex = /"([^"]+)"|(\S+)/g;
var match;
while ((match = regex.exec(input)) !== null) {
var token = match[1] || match[2] || '';
if (!token) continue;
token.split('|').forEach(function(part) {
var cleaned = part.trim();
if (!cleaned) return;
terms.push(cleaned);
});
}
return terms;
}
async function SearchIt() {
await executeSearch(false);
}
async function SearchWithinResults() {
if (!lastResultIndexes.length) {
renderMessage('请先执行一次完整搜索再使用结果内搜索', true);
return;
}
await executeSearch(true);
}
async function executeSearch(searchWithin) {
var keyword = document.getElementById('keyword').value.trim();
if (!keyword) {
renderMessage('请输入关键词后再搜索', true);
return;
}
var titleOnly = document.getElementById('titleOnly').checked;
var categoryValue = categorySelect ? (categorySelect.value || 'all') : 'all';
renderMessage('正在搜索,请稍候…', true);
words = extractHighlightTerms(keyword);
var params = new URLSearchParams({
keyword: keyword,
titleOnly: titleOnly,
page: 1,
pageSize: 100
});
params.set('category', categoryValue);
if (searchWithin) {
params.set('baseIndexes', lastResultIndexes.join(','));
}
try {
var response = await fetch(API_BASE + '/api/search?' + params.toString());
if (!response.ok) {
throw new Error('搜索失败');
}
var data = await response.json();
displayResults(data);
} catch (e) {
console.error('API 搜索失败:', e);
lastResultIndexes = [];
renderMessage('搜索失败,请确认后端已运行 `node server.js`', true);
}
}
function displayResults(data) {
var listElem = document.getElementById('resultsList');
listElem.innerHTML = '';
if (data.results && data.results.length > 0) {
lastResultIndexes = data.results.map(function(item) { return item.index; });
document.getElementById('resultsCount').textContent = data.total;
document.getElementById('resultsInfo').style.display = 'block';
data.results.forEach(function(item, idx) {
var li = document.createElement('li');
li.className = 'result-item' + (idx === 0 ? ' selected' : '');
var sourcePath = resolveSourcePath(item);
var displayTitle = resolveTitle(item, sourcePath);
li.dataset.url = item.path || '';
li.dataset.title = displayTitle;
li.dataset.source = sourcePath;
li.dataset.category = item.category || '';
li._previewText = resolvePreviewText(item);
var titleCell = document.createElement('div');
titleCell.className = 'result-main-title';
var titleText = document.createElement('div');
titleText.className = 'result-title-text';
titleText.textContent = displayTitle;
var rankBadge = document.createElement('div');
rankBadge.className = 'result-rank';
rankBadge.textContent = '相关度 ' + item.rank;
titleCell.appendChild(titleText);
titleCell.appendChild(rankBadge);
var sourceCell = document.createElement('div');
sourceCell.className = 'result-meta';
var metaParts = [];
if (item.category) {
metaParts.push(item.category);
}
if (sourcePath) {
metaParts.push(sourcePath);
}
sourceCell.textContent = metaParts.join(' · ') || '—';
li.appendChild(titleCell);
li.appendChild(sourceCell);
li.addEventListener('click', function(event) {
selectItem(li, event);
if (li.dataset.url) {
hidePreview();
viewItem(li.dataset.url);
}
});
li.addEventListener('mouseenter', function(event) {
showPreview(li, event);
});
li.addEventListener('mousemove', movePreview);
li.addEventListener('mouseleave', hidePreview);
listElem.appendChild(li);
});
var first = listElem.querySelector('.result-item');
if (first) {
selectItem(first, null);
}
} else {
lastResultIndexes = [];
document.getElementById('resultsInfo').style.display = 'none';
renderMessage('未找到相关结果,请尝试调整关键词', true);
}
}
function showPreview(elem, event) {
if (!previewTooltip) return;
var title = (elem.dataset.title || '预览').trim();
var snippet = (elem._previewText || '').trim();
previewTitleElem.textContent = title || '预览';
if (snippet) {
previewContentElem.classList.remove('preview-tooltip__empty');
previewContentElem.innerHTML = renderSnippet(snippet);
} else {
previewContentElem.classList.add('preview-tooltip__empty');
previewContentElem.textContent = '暂无可预览的内容片段';
}
previewTooltip.classList.add('visible');
var baselineY;
if (event && typeof event.clientY === 'number') {
baselineY = event.clientY;
} else {
var rect = elem.getBoundingClientRect();
baselineY = rect.top + rect.height / 2;
}
positionPreview(baselineY);
}
function movePreview(event) {
if (!previewTooltip || !previewTooltip.classList.contains('visible')) return;
positionPreview(event.clientY);
}
function hidePreview() {
if (!previewTooltip) return;
previewTooltip.classList.remove('visible');
previewTooltip.style.left = '-9999px';
previewTooltip.style.top = '-9999px';
}
function positionPreview(cursorY) {
if (!previewTooltip) return;
var tooltip = previewTooltip;
var padding = 16;
var tooltipWidth = tooltip.offsetWidth;
var tooltipHeight = tooltip.offsetHeight;
var targetX = window.innerWidth - tooltipWidth - padding;
var targetY = typeof cursorY === 'number' ? cursorY - tooltipHeight / 2 : (window.innerHeight - tooltipHeight) / 2;
targetY = Math.max(padding, Math.min(window.innerHeight - tooltipHeight - padding, targetY));
tooltip.style.left = targetX + 'px';
tooltip.style.top = targetY + 'px';
}
function renderSnippet(snippet) {
var truncated = snippet.length > 900 ? snippet.slice(0, 900) + '…' : snippet;
var safeSnippet = escapeHtml(truncated || '');
words.forEach(function(word) {
var escaped = escapeRegExp(word);
if (!escaped) return;
var regex = new RegExp(escaped, 'gi');
safeSnippet = safeSnippet.replace(regex, function(match) {
return '<mark>' + match + '</mark>';
});
});
return safeSnippet
.replace(/\r\n/g, '<br>')
.replace(/\r/g, '<br>')
.replace(/\n/g, '<br>');
}
function renderMessage(message, clearPreview) {
document.getElementById('resultsInfo').style.display = 'none';
var listElem = document.getElementById('resultsList');
listElem.innerHTML = '<li class="empty-state"><div class="empty-text">' + escapeHtml(message) + '</div></li>';
if (clearPreview) {
hidePreview();
}
}
function getContentWindow() {
var current;
try {
// Search page may sit inside nav -> webhelpframe -> main frames.
// Start here, then walk parents until the sibling content frame appears.
current = window;
} catch (e) {
current = window;
}
for (var depth = 0; current && depth < 12; depth++) {
try {
var namedContent = current.frames && current.frames['content'];
if (namedContent && namedContent.document) {
searchLog('content frame found by name', { depth: depth, name: current.name || '' });
return namedContent;
}
} catch (namedFrameError) {
searchLog('named content lookup failed', { depth: depth, error: String(namedFrameError && namedFrameError.message || namedFrameError) });
}
try {
var ownerDocument = current.document;
var frame = ownerDocument && ownerDocument.getElementById('content');
if (!frame && ownerDocument && ownerDocument.getElementsByName) {
var namedFrames = ownerDocument.getElementsByName('content');
frame = namedFrames && namedFrames[0];
}
if (frame && frame.contentWindow && frame.contentWindow.document) {
searchLog('content frame found by DOM', { depth: depth, name: current.name || '' });
return frame.contentWindow;
}
if (!current.parent || current.parent === current) break;
current = current.parent;
} catch (e2) {
searchLog('parent frame walk failed', { depth: depth, error: String(e2 && e2.message || e2) });
break;
}
}
searchLog('content frame walk exhausted');
return null;
}
function getContentFrame() {
var contentWin = getContentWindow();
if (!contentWin) return null;
try {
var ownerDocument = contentWin.frameElement && contentWin.frameElement.ownerDocument;
return ownerDocument ? contentWin.frameElement : null;
} catch (e) {
return null;
}
}
function contentLocationMatches(contentWin, expectedUrl) {
if (!contentWin || !expectedUrl) return true;
try {
var expectedLink = document.createElement('a');
expectedLink.href = expectedUrl;
var expectedPath = (expectedLink.pathname || '').replace(/\/$/, '');
var currentPath = (contentWin.location.pathname || '').replace(/\/$/, '');
if (!expectedPath || !currentPath) return true;
var expectedDecoded = decodeURIComponent(expectedPath).toLowerCase();
var currentDecoded = decodeURIComponent(currentPath).toLowerCase();
return currentDecoded === expectedDecoded ||
currentDecoded.slice(-expectedDecoded.length - 1) === '/' + expectedDecoded;
} catch (e) {
return true;
}
}
function clearContentHighlights(contentDoc) {
if (!contentDoc) return;
var state = contentDoc.__searchHighlightState;
if (state && state.keydownHandler) {
contentDoc.removeEventListener('keydown', state.keydownHandler);
}
var navigator = contentDoc.getElementById('searchHighlightNavigator');
if (navigator && navigator.parentNode) {
navigator.parentNode.removeChild(navigator);
}
var marks = contentDoc.querySelectorAll('mark[data-search-highlight="true"]');
for (var i = 0; i < marks.length; i++) {
var mark = marks[i];
if (mark.parentNode) {
mark.parentNode.replaceChild(contentDoc.createTextNode(mark.textContent || ''), mark);
}
}
contentDoc.__searchHighlightState = null;
}
function ensureContentHighlightStyle(contentDoc) {
if (!contentDoc || !contentDoc.head) return;
if (contentDoc.getElementById('searchHighlightStyle')) return;
var style = contentDoc.createElement('style');
style.id = 'searchHighlightStyle';
style.textContent =
'mark[data-search-highlight="true"] {' +
' background: #fde68a; color: inherit; padding: 1px 2px; border-radius: 2px;' +
' font-weight: 500;' +
'}' +
'#searchHighlightNavigator {' +
' position: fixed; top: 12px; right: 16px; z-index: 2147483647;' +
' display: flex; align-items: center; gap: 6px; padding: 6px 8px;' +
' border: 1px solid rgba(148, 163, 184, .55); border-radius: 8px;' +
' background: rgba(255, 255, 255, .96); color: #1e293b;' +
' box-shadow: 0 4px 14px rgba(15, 23, 42, .18);' +
' font: 12px/1.2 Arial, sans-serif;' +
'}' +
'#searchHighlightNavigator button {' +
' border: 0; border-radius: 5px; padding: 4px 7px; cursor: pointer;' +
' background: #e0e7ff; color: #1e3a8a; font: inherit;' +
'}' +
'#searchHighlightNavigator button:hover:not(:disabled) { background: #c7d2fe; }' +
'#searchHighlightNavigator button:disabled { opacity: .45; cursor: default; }' +
'#searchHighlightNavigator .search-highlight-count {' +
' min-width: 42px; text-align: center; white-space: nowrap; font-weight: 600;' +
'}';
contentDoc.head.appendChild(style);
}
function updateHighlightNavigator(state) {
if (!state || !state.counter) return;
var total = state.marks.length;
state.counter.textContent = total ? (state.index + 1) + ' / ' + total : '未找到';
state.previous.disabled = total < 2;
state.next.disabled = total < 2;
}
function jumpToHighlight(state, index, smooth) {
if (!state || !state.marks.length) return;
if (state.index >= 0 && state.marks[state.index]) {
state.marks[state.index].removeAttribute('data-search-active');
state.marks[state.index].style.background = '';
state.marks[state.index].style.color = '';
state.marks[state.index].style.outline = '';
}
state.index = (index + state.marks.length) % state.marks.length;
var mark = state.marks[state.index];
mark.setAttribute('data-search-active', 'true');
mark.style.background = '#f59e0b';
mark.style.color = '#111827';
mark.style.outline = '2px solid rgba(245, 158, 11, .45)';
updateHighlightNavigator(state);
try {
mark.scrollIntoView({
behavior: smooth ? 'smooth' : 'auto',
block: 'center',
inline: 'nearest'
});
} catch (e) {
mark.scrollIntoView(true);
}
}
function createHighlightNavigator(contentDoc, marks) {
var navigator = contentDoc.createElement('div');
navigator.id = 'searchHighlightNavigator';
navigator.setAttribute('role', 'navigation');
navigator.setAttribute('aria-label', '搜索关键词导航');
var previous = contentDoc.createElement('button');
previous.type = 'button';
previous.textContent = '上一个';
previous.setAttribute('aria-label', '上一个关键词');
var counter = contentDoc.createElement('span');
counter.className = 'search-highlight-count';
var next = contentDoc.createElement('button');
next.type = 'button';
next.textContent = '下一个';
next.setAttribute('aria-label', '下一个关键词');
navigator.appendChild(previous);
navigator.appendChild(counter);
navigator.appendChild(next);
contentDoc.body.appendChild(navigator);
var state = {
marks: marks,
index: -1,
navigator: navigator,
previous: previous,
next: next,
counter: counter,
keydownHandler: null
};
previous.addEventListener('click', function() {
jumpToHighlight(state, state.index - 1, true);
});
next.addEventListener('click', function() {
jumpToHighlight(state, state.index + 1, true);
});
state.keydownHandler = function(event) {
if (!event.altKey || (event.key !== 'ArrowUp' && event.key !== 'ArrowDown')) return;
event.preventDefault();
jumpToHighlight(state, state.index + (event.key === 'ArrowUp' ? -1 : 1), true);
};
contentDoc.addEventListener('keydown', state.keydownHandler);
updateHighlightNavigator(state);
return state;
}
function highlightInContent(requestId, expectedUrl) {
if (words.length === 0) return;
var attempts = 0;
var maxAttempts = 30;
searchLog('highlight scheduled', { requestId: requestId, expectedUrl: expectedUrl, words: words });
function retry() {
if (requestId && requestId !== highlightRequestId) return;
attempts++;
if (attempts >= maxAttempts) return;
if (attempts === 1 || attempts % 5 === 0) {
searchLog('highlight retry', { requestId: requestId, attempts: attempts });
}
setTimeout(tryHighlight, 200);
}
function tryHighlight() {
if (requestId && requestId !== highlightRequestId) return;
try {
var contentWin = getContentWindow();
if (!contentWin) {
if (attempts === 0 || attempts % 5 === 0) searchLog('content frame not found', { requestId: requestId, attempts: attempts });
retry();
return;
}
var contentDoc = contentWin.document;
if (!contentDoc || !contentDoc.body || contentDoc.readyState === 'loading') {
if (attempts === 0 || attempts % 5 === 0) {
searchLog('content document not ready', {
requestId: requestId,
attempts: attempts,
readyState: contentDoc && contentDoc.readyState,
href: contentWin.location && contentWin.location.href
});
}
retry();
return;
}
if (!contentLocationMatches(contentWin, expectedUrl)) {
if (attempts === 0 || attempts % 5 === 0) {
searchLog('content URL mismatch', {
requestId: requestId,
attempts: attempts,
expectedUrl: expectedUrl,
actualUrl: contentWin.location.href
});
}
retry();
return;
}
clearContentHighlights(contentDoc);
ensureContentHighlightStyle(contentDoc);
var terms = words.filter(function(word, index, list) {
return word && list.indexOf(word) === index;
}).sort(function(a, b) {
return b.length - a.length;
});
if (!terms.length) return;
var regex = new RegExp('(' + terms.map(escapeRegExp).join('|') + ')', 'gi');
var walker = contentDoc.createTreeWalker(contentDoc.body, NodeFilter.SHOW_TEXT, null, false);
var nodesToProcess = [];
var node;
while ((node = walker.nextNode())) {
var tagName = node.parentNode && node.parentNode.tagName;
if (tagName !== 'SCRIPT' && tagName !== 'STYLE' && tagName !== 'NOSCRIPT' && tagName !== 'MARK') {
nodesToProcess.push(node);
}
}
nodesToProcess.forEach(function(textNode) {
var text = textNode.nodeValue || '';
regex.lastIndex = 0;
var match;
var lastIndex = 0;
var fragment = contentDoc.createDocumentFragment();
var found = false;
while ((match = regex.exec(text)) !== null) {
found = true;
if (match.index > lastIndex) {
fragment.appendChild(contentDoc.createTextNode(text.slice(lastIndex, match.index)));
}
var mark = contentDoc.createElement('mark');
mark.setAttribute('data-search-highlight', 'true');
mark.textContent = match[0];
fragment.appendChild(mark);
lastIndex = match.index + match[0].length;
if (match[0].length === 0) regex.lastIndex++;
}
if (!found) return;
if (lastIndex < text.length) {
fragment.appendChild(contentDoc.createTextNode(text.slice(lastIndex)));
}
textNode.parentNode.replaceChild(fragment, textNode);
});
var marks = Array.prototype.slice.call(contentDoc.querySelectorAll('mark[data-search-highlight="true"]'));
var state = createHighlightNavigator(contentDoc, marks);
contentDoc.__searchHighlightState = state;
searchLog('highlight complete', {
requestId: requestId,
href: contentWin.location.href,
terms: terms,
matches: marks.length
});
if (marks.length) {
jumpToHighlight(state, 0, false);
}
} catch (e) {
if (attempts === 0 || attempts % 5 === 0) {
searchLog('highlight exception', { requestId: requestId, attempts: attempts, error: String(e && e.message || e) });
}
retry();
}
}
setTimeout(tryHighlight, 0);
}
function viewSelected() {
var selected = document.querySelector('.result-item.selected');
if (selected) {
var url = selected.dataset.url;
if (url) {