Update index.html
Browse files- index.html +275 -14
index.html
CHANGED
|
@@ -124,8 +124,9 @@ textarea{width:100%;height:460px;resize:vertical;border:1px solid var(--input-bo
|
|
| 124 |
.control{display:flex;flex-direction:column;gap:5px}
|
| 125 |
.control label{font-size:12px;color:var(--status)}
|
| 126 |
.control input{width:100px;padding:8px;border:1px solid var(--input-border);border-radius:7px;background:var(--input-bg);color:var(--text)}
|
| 127 |
-
button{border:0;border-radius:8px;padding:10px 18px;font-size:14px;cursor:pointer}
|
| 128 |
.primary{background:var(--btn-primary-bg);color:var(--btn-primary-text)}
|
|
|
|
| 129 |
button:disabled{opacity:.5;cursor:not-allowed}
|
| 130 |
.status{margin-left:auto;color:var(--status);font-size:14px}
|
| 131 |
.results-panel #output{max-height:75vh;overflow-y:auto;padding-right:4px}
|
|
@@ -133,7 +134,9 @@ button:disabled{opacity:.5;cursor:not-allowed}
|
|
| 133 |
.found-source{display:flex;flex-wrap:wrap;align-items:center;gap:5px 3px;font-size:14px;margin-bottom:8px}
|
| 134 |
.found-label{color:var(--note-text)}
|
| 135 |
.found-colon{color:var(--note-text)}
|
| 136 |
-
.crumb{display:inline-block;font-weight:800;padding:2px 8px;border-radius:6px;line-height:1.4}
|
|
|
|
|
|
|
| 137 |
.crumb-book{background:var(--crumb-book-bg);color:var(--crumb-book-text)}
|
| 138 |
.crumb-section{background:var(--crumb-section-bg);color:var(--crumb-section-text)}
|
| 139 |
.crumb-article{background:var(--crumb-article-bg);color:var(--crumb-article-text)}
|
|
@@ -159,6 +162,13 @@ button:disabled{opacity:.5;cursor:not-allowed}
|
|
| 159 |
.input-hint.empty-hint{color:var(--hint-empty)}
|
| 160 |
.pct-badge{display:inline-block;font-weight:800;font-size:13px;padding:2px 8px;border-radius:6px;margin-right:6px;background:var(--pct-bg);color:var(--pct-text)}
|
| 161 |
.book-match-error{font-size:13px;color:var(--book-error-text);background:var(--book-error-bg);border:1px solid var(--book-error-border);border-radius:8px;padding:8px 12px}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
@media(max-width:900px){
|
| 163 |
.main-grid{grid-template-columns:1fr}
|
| 164 |
.status{width:100%;margin-left:0}
|
|
@@ -171,7 +181,7 @@ button:disabled{opacity:.5;cursor:not-allowed}
|
|
| 171 |
<h1 style="margin:0">Поиск совпадений с книгами</h1>
|
| 172 |
<button class="theme-toggle" id="themeToggle" onclick="toggleTheme()">🌙 Тёмная</button>
|
| 173 |
</div>
|
| 174 |
-
<div class="subtitle">Вставьте искомый текст справа и нажмите «Найти совпадения» — слева появятся найденные фрагменты из книг.</div>
|
| 175 |
|
| 176 |
<div class="main-grid">
|
| 177 |
<section class="panel results-panel">
|
|
@@ -180,7 +190,7 @@ button:disabled{opacity:.5;cursor:not-allowed}
|
|
| 180 |
</section>
|
| 181 |
<section class="panel">
|
| 182 |
<h2>Искомый текст</h2>
|
| 183 |
-
<textarea id="chunksText" placeholder="
|
| 184 |
<button class="clear-btn" onclick="clearAll()">🗑 Очистить</button>
|
| 185 |
<div id="chunksHint" class="input-hint empty-hint">Вставьте текст</div>
|
| 186 |
</section>
|
|
@@ -190,8 +200,17 @@ button:disabled{opacity:.5;cursor:not-allowed}
|
|
| 190 |
<div class="control"><label>Порог схожести, %</label><input id="threshold" type="number" value="60" min="0" max="100"></div>
|
| 191 |
<label class="auto-label"><input type="checkbox" id="autoMode"> Авто-подбор порога</label>
|
| 192 |
<button id="run" class="primary">🔎 Найти совпадения</button>
|
|
|
|
| 193 |
<div id="status" class="status">Готово</div>
|
| 194 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 195 |
</div>
|
| 196 |
|
| 197 |
<div id="progressOverlay" class="progress-overlay" style="display:none">
|
|
@@ -223,6 +242,7 @@ function clearAll(){
|
|
| 223 |
$("output").className="empty";
|
| 224 |
$("output").innerHTML="Вставьте текст справа и нажмите «Найти совпадения».";
|
| 225 |
$("status").textContent="Готово";
|
|
|
|
| 226 |
}
|
| 227 |
window.clearAll=clearAll;
|
| 228 |
|
|
@@ -405,7 +425,17 @@ function buildIndex(articles){
|
|
| 405 |
for(const [g,val] of v)v.set(g,val/norm);
|
| 406 |
return v;
|
| 407 |
});
|
| 408 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 409 |
}
|
| 410 |
|
| 411 |
function vectorFor(text,index){
|
|
@@ -433,11 +463,29 @@ function cosine(a,b){
|
|
| 433 |
|
| 434 |
function nearest(text,index){
|
| 435 |
const v=vectorFor(text,index);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 436 |
const candidates=[];
|
| 437 |
-
|
| 438 |
-
const
|
| 439 |
-
|
| 440 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 441 |
candidates.sort((a,b)=>b.sim-a.sim);
|
| 442 |
return candidates.slice(0,5);
|
| 443 |
}
|
|
@@ -470,7 +518,7 @@ function processRange(sentences,combs,opt,start,end){
|
|
| 470 |
}
|
| 471 |
if(best){
|
| 472 |
const before=processRange(sentences,combs,opt,start,best.i-1);
|
| 473 |
-
const match={text:best.text,is_match:true,article:best.article,fragment:best.match,score:best.sim};
|
| 474 |
const after=processRange(sentences,combs,opt,best.j+1,end);
|
| 475 |
return [...before,match,...after];
|
| 476 |
}else{
|
|
@@ -527,6 +575,7 @@ function findMatchesInChunk(text,index,opt){
|
|
| 527 |
const m=merged[merged.length-1];
|
| 528 |
m.text+=" "+s.text;
|
| 529 |
m.fragment+=" "+s.fragment;
|
|
|
|
| 530 |
m.score=Math.max(m.score,s.score);
|
| 531 |
}else{
|
| 532 |
merged.push({...s});
|
|
@@ -583,6 +632,7 @@ function findMatchesAdaptive(text,index,baseOpt){
|
|
| 583 |
const m=merged[merged.length-1];
|
| 584 |
m.text+=" "+s.text;
|
| 585 |
m.fragment+=" "+s.fragment;
|
|
|
|
| 586 |
m.score=Math.max(m.score,s.score);
|
| 587 |
}else{
|
| 588 |
merged.push({...s});
|
|
@@ -606,8 +656,8 @@ function hexToRgba(hex,alpha){
|
|
| 606 |
return `rgba(${r},${g},${b},${alpha})`;
|
| 607 |
}
|
| 608 |
|
| 609 |
-
/* === Строка с указанием источника (Книга → Раздел → Статья → Подзаголовок), каждая часть — цветная крошка === */
|
| 610 |
-
function leafPath(leafIdxStr){
|
| 611 |
const leaf=bookLeaves[Number(leafIdxStr)];
|
| 612 |
const levels=[];
|
| 613 |
if(leaf){
|
|
@@ -617,8 +667,94 @@ function leafPath(leafIdxStr){
|
|
| 617 |
if(leaf.subheading)levels.push({cls:"crumb-subheading",text:leaf.subheading});
|
| 618 |
}
|
| 619 |
if(!levels.length)return `<span class="crumb crumb-book">Книга</span>`;
|
| 620 |
-
return levels.map(l=>`<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 621 |
}
|
|
|
|
| 622 |
|
| 623 |
function showProgress(){
|
| 624 |
$("progressOverlay").style.display="flex";
|
|
@@ -733,6 +869,7 @@ async function loadBooksData(){
|
|
| 733 |
/* ==================== Поиск и отображение результатов ==================== */
|
| 734 |
function renderResults(data,useAdaptive){
|
| 735 |
const out=$("output");
|
|
|
|
| 736 |
if(data.matched===0){
|
| 737 |
out.className="";
|
| 738 |
out.innerHTML=`<div class="unique-banner">✅ Проверено текстов: ${data.chunks.length}. Совпадений с книгами не найдено.</div>`;
|
|
@@ -763,8 +900,11 @@ function renderResults(data,useAdaptive){
|
|
| 763 |
groupByLeaf.get(m.article).items.push(m);
|
| 764 |
}
|
| 765 |
for(const g of groups){
|
|
|
|
|
|
|
|
|
|
| 766 |
html+=`<div class="found-item">`;
|
| 767 |
-
html+=`<div class="found-source"><span class="found-label">Найдено в</span> ${leafPath(g.leaf)}<span class="found-colon">:</span></div>`;
|
| 768 |
g.items.forEach((m,i)=>{
|
| 769 |
html+=`<div class="found-quote${i>0?" found-quote-sep":""}"><span class="pct-badge">${Math.round(m.score)}%</span> — «${escapeHtml(m.fragment)}»</div>`;
|
| 770 |
});
|
|
@@ -780,6 +920,7 @@ async function runSearch(){
|
|
| 780 |
if(!chunkRaw.trim()){ alert("Нужно вставить искомый текст."); return; }
|
| 781 |
$("status").textContent="Обработка...";
|
| 782 |
$("run").disabled=true;
|
|
|
|
| 783 |
showProgress();
|
| 784 |
await new Promise(r=>setTimeout(r,50));
|
| 785 |
try{
|
|
@@ -822,6 +963,126 @@ async function runSearch(){
|
|
| 822 |
}
|
| 823 |
}
|
| 824 |
$("run").addEventListener("click",runSearch);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 825 |
</script>
|
| 826 |
</body>
|
| 827 |
</html>
|
|
|
|
| 124 |
.control{display:flex;flex-direction:column;gap:5px}
|
| 125 |
.control label{font-size:12px;color:var(--status)}
|
| 126 |
.control input{width:100px;padding:8px;border:1px solid var(--input-border);border-radius:7px;background:var(--input-bg);color:var(--text)}
|
| 127 |
+
button{border:0;border-radius:8px;padding:10px 18px;font-size:14px;cursor:pointer;font-family:inherit}
|
| 128 |
.primary{background:var(--btn-primary-bg);color:var(--btn-primary-text)}
|
| 129 |
+
.secondary{background:var(--btn-bg);color:var(--btn-text)}
|
| 130 |
button:disabled{opacity:.5;cursor:not-allowed}
|
| 131 |
.status{margin-left:auto;color:var(--status);font-size:14px}
|
| 132 |
.results-panel #output{max-height:75vh;overflow-y:auto;padding-right:4px}
|
|
|
|
| 134 |
.found-source{display:flex;flex-wrap:wrap;align-items:center;gap:5px 3px;font-size:14px;margin-bottom:8px}
|
| 135 |
.found-label{color:var(--note-text)}
|
| 136 |
.found-colon{color:var(--note-text)}
|
| 137 |
+
.crumb{display:inline-block;font-weight:800;padding:2px 8px;border-radius:6px;line-height:1.4;font-family:inherit;transition:filter 0.15s}
|
| 138 |
+
button.crumb{cursor:pointer}
|
| 139 |
+
button.crumb:hover{filter:brightness(0.9)}
|
| 140 |
.crumb-book{background:var(--crumb-book-bg);color:var(--crumb-book-text)}
|
| 141 |
.crumb-section{background:var(--crumb-section-bg);color:var(--crumb-section-text)}
|
| 142 |
.crumb-article{background:var(--crumb-article-bg);color:var(--crumb-article-text)}
|
|
|
|
| 162 |
.input-hint.empty-hint{color:var(--hint-empty)}
|
| 163 |
.pct-badge{display:inline-block;font-weight:800;font-size:13px;padding:2px 8px;border-radius:6px;margin-right:6px;background:var(--pct-bg);color:var(--pct-text)}
|
| 164 |
.book-match-error{font-size:13px;color:var(--book-error-text);background:var(--book-error-bg);border:1px solid var(--book-error-border);border-radius:8px;padding:8px 12px}
|
| 165 |
+
.article-panel{margin-top:20px}
|
| 166 |
+
.article-panel-header{display:flex;justify-content:space-between;align-items:flex-start;flex-wrap:wrap;gap:10px;margin-bottom:12px}
|
| 167 |
+
.article-body{max-height:65vh;overflow-y:auto;font-size:14.5px;line-height:1.85;padding-right:6px}
|
| 168 |
+
.article-body p{margin:12px 0}
|
| 169 |
+
.article-body mark{background:var(--match-bg);color:#1a1a1a;padding:1px 2px;border-radius:2px}
|
| 170 |
+
.word-count-list{margin:2px 0 0;padding-left:20px}
|
| 171 |
+
.word-count-list li{font-size:14px;line-height:1.8;color:var(--note-match-text)}
|
| 172 |
@media(max-width:900px){
|
| 173 |
.main-grid{grid-template-columns:1fr}
|
| 174 |
.status{width:100%;margin-left:0}
|
|
|
|
| 181 |
<h1 style="margin:0">Поиск совпадений с книгами</h1>
|
| 182 |
<button class="theme-toggle" id="themeToggle" onclick="toggleTheme()">🌙 Тёмная</button>
|
| 183 |
</div>
|
| 184 |
+
<div class="subtitle">Вставьте искомый текст справа и нажмите «Найти совпадения» — слева появятся найденные фрагменты из книг. Либо перечислите слова через запятую и нажмите «Посчитать слова», чтобы узнать, сколько раз они встречаются в каждой статье.</div>
|
| 185 |
|
| 186 |
<div class="main-grid">
|
| 187 |
<section class="panel results-panel">
|
|
|
|
| 190 |
</section>
|
| 191 |
<section class="panel">
|
| 192 |
<h2>Искомый текст</h2>
|
| 193 |
+
<textarea id="chunksText" placeholder="Кусок текста для поиска совпадений — или слова через запятую для подсчёта, напр.: Мария, зачатие"></textarea>
|
| 194 |
<button class="clear-btn" onclick="clearAll()">🗑 Очистить</button>
|
| 195 |
<div id="chunksHint" class="input-hint empty-hint">Вставьте текст</div>
|
| 196 |
</section>
|
|
|
|
| 200 |
<div class="control"><label>Порог схожести, %</label><input id="threshold" type="number" value="60" min="0" max="100"></div>
|
| 201 |
<label class="auto-label"><input type="checkbox" id="autoMode"> Авто-подбор порога</label>
|
| 202 |
<button id="run" class="primary">🔎 Найти совпадения</button>
|
| 203 |
+
<button id="countWords" class="secondary">🔢 Посчитать слова</button>
|
| 204 |
<div id="status" class="status">Готово</div>
|
| 205 |
</div>
|
| 206 |
+
|
| 207 |
+
<section class="panel article-panel" id="articlePanel" style="display:none">
|
| 208 |
+
<div class="article-panel-header">
|
| 209 |
+
<h2 id="articleTitle" style="margin:0">Статья</h2>
|
| 210 |
+
<button class="clear-btn" onclick="closeArticle()">✕ Закрыть</button>
|
| 211 |
+
</div>
|
| 212 |
+
<div id="articleBody" class="article-body"></div>
|
| 213 |
+
</section>
|
| 214 |
</div>
|
| 215 |
|
| 216 |
<div id="progressOverlay" class="progress-overlay" style="display:none">
|
|
|
|
| 242 |
$("output").className="empty";
|
| 243 |
$("output").innerHTML="Вставьте текст справа и нажмите «Найти совпадения».";
|
| 244 |
$("status").textContent="Готово";
|
| 245 |
+
$("articlePanel").style.display="none";
|
| 246 |
}
|
| 247 |
window.clearAll=clearAll;
|
| 248 |
|
|
|
|
| 425 |
for(const [g,val] of v)v.set(g,val/norm);
|
| 426 |
return v;
|
| 427 |
});
|
| 428 |
+
// Обратный индекс по значимым словам (4+ символа) — резко сужает круг
|
| 429 |
+
// кандидатов при поиске в больших books.json вместо сравнения со ВСЕМИ предложениями.
|
| 430 |
+
const wordIndex=new Map();
|
| 431 |
+
docs.forEach((doc,i)=>{
|
| 432 |
+
const words=new Set(doc.split(/\s+/).filter(w=>w.length>=4));
|
| 433 |
+
for(const w of words){
|
| 434 |
+
if(!wordIndex.has(w))wordIndex.set(w,[]);
|
| 435 |
+
wordIndex.get(w).push(i);
|
| 436 |
+
}
|
| 437 |
+
});
|
| 438 |
+
return {sentences,titles,vectors,df,N,wordIndex};
|
| 439 |
}
|
| 440 |
|
| 441 |
function vectorFor(text,index){
|
|
|
|
| 463 |
|
| 464 |
function nearest(text,index){
|
| 465 |
const v=vectorFor(text,index);
|
| 466 |
+
const queryWords=preprocess(text).split(/\s+/).filter(w=>w.length>=4);
|
| 467 |
+
let candidateIdx=null;
|
| 468 |
+
if(queryWords.length){
|
| 469 |
+
const set=new Set();
|
| 470 |
+
for(const w of queryWords){
|
| 471 |
+
const list=index.wordIndex.get(w);
|
| 472 |
+
if(list)for(const i of list)set.add(i);
|
| 473 |
+
}
|
| 474 |
+
candidateIdx=set;
|
| 475 |
+
}
|
| 476 |
const candidates=[];
|
| 477 |
+
if(candidateIdx){
|
| 478 |
+
for(const i of candidateIdx){
|
| 479 |
+
const s=cosine(v,index.vectors[i]);
|
| 480 |
+
candidates.push({index:i,sim:s*100});
|
| 481 |
+
}
|
| 482 |
+
}else{
|
| 483 |
+
// нет значимых слов в запросе (редкий случай короткого текста) — сравниваем со всеми
|
| 484 |
+
index.vectors.forEach((iv,i)=>{
|
| 485 |
+
const s=cosine(v,iv);
|
| 486 |
+
candidates.push({index:i,sim:s*100});
|
| 487 |
+
});
|
| 488 |
+
}
|
| 489 |
candidates.sort((a,b)=>b.sim-a.sim);
|
| 490 |
return candidates.slice(0,5);
|
| 491 |
}
|
|
|
|
| 518 |
}
|
| 519 |
if(best){
|
| 520 |
const before=processRange(sentences,combs,opt,start,best.i-1);
|
| 521 |
+
const match={text:best.text,is_match:true,article:best.article,fragment:best.match,fragments:[best.match],score:best.sim};
|
| 522 |
const after=processRange(sentences,combs,opt,best.j+1,end);
|
| 523 |
return [...before,match,...after];
|
| 524 |
}else{
|
|
|
|
| 575 |
const m=merged[merged.length-1];
|
| 576 |
m.text+=" "+s.text;
|
| 577 |
m.fragment+=" "+s.fragment;
|
| 578 |
+
m.fragments=(m.fragments||[m.fragment]).concat(s.fragments||[s.fragment]);
|
| 579 |
m.score=Math.max(m.score,s.score);
|
| 580 |
}else{
|
| 581 |
merged.push({...s});
|
|
|
|
| 632 |
const m=merged[merged.length-1];
|
| 633 |
m.text+=" "+s.text;
|
| 634 |
m.fragment+=" "+s.fragment;
|
| 635 |
+
m.fragments=(m.fragments||[m.fragment]).concat(s.fragments||[s.fragment]);
|
| 636 |
m.score=Math.max(m.score,s.score);
|
| 637 |
}else{
|
| 638 |
merged.push({...s});
|
|
|
|
| 656 |
return `rgba(${r},${g},${b},${alpha})`;
|
| 657 |
}
|
| 658 |
|
| 659 |
+
/* === Строка с указанием источника (Книга → Раздел → Статья → Подзаголовок), каждая часть — цветная крошка, клик открывает статью целиком === */
|
| 660 |
+
function leafPath(leafIdxStr,groupId){
|
| 661 |
const leaf=bookLeaves[Number(leafIdxStr)];
|
| 662 |
const levels=[];
|
| 663 |
if(leaf){
|
|
|
|
| 667 |
if(leaf.subheading)levels.push({cls:"crumb-subheading",text:leaf.subheading});
|
| 668 |
}
|
| 669 |
if(!levels.length)return `<span class="crumb crumb-book">Книга</span>`;
|
| 670 |
+
return levels.map(l=>`<button type="button" class="crumb ${l.cls}" onclick="openArticle(${groupId})">${escapeHtml(l.text)}</button>`).join(`<span class="crumb-sep">→</span>`);
|
| 671 |
+
}
|
| 672 |
+
|
| 673 |
+
/* === Подсветка найденного в полном тексте статьи (панель внизу) === */
|
| 674 |
+
function mergeRanges(ranges){
|
| 675 |
+
if(!ranges.length)return [];
|
| 676 |
+
ranges.sort((a,b)=>a[0]-b[0]);
|
| 677 |
+
const merged=[ranges[0].slice()];
|
| 678 |
+
for(let i=1;i<ranges.length;i++){
|
| 679 |
+
const r=ranges[i];
|
| 680 |
+
const last=merged[merged.length-1];
|
| 681 |
+
if(r[0]<=last[1]){
|
| 682 |
+
last[1]=Math.max(last[1],r[1]);
|
| 683 |
+
}else{
|
| 684 |
+
merged.push(r.slice());
|
| 685 |
+
}
|
| 686 |
+
}
|
| 687 |
+
return merged;
|
| 688 |
+
}
|
| 689 |
+
function applyRanges(fullText,ranges){
|
| 690 |
+
if(!ranges.length)return escapeHtml(fullText);
|
| 691 |
+
let html="";
|
| 692 |
+
let pos=0;
|
| 693 |
+
for(const [start,end] of ranges){
|
| 694 |
+
html+=escapeHtml(fullText.slice(pos,start));
|
| 695 |
+
html+=`<mark>${escapeHtml(fullText.slice(start,end))}</mark>`;
|
| 696 |
+
pos=end;
|
| 697 |
+
}
|
| 698 |
+
html+=escapeHtml(fullText.slice(pos));
|
| 699 |
+
return html;
|
| 700 |
+
}
|
| 701 |
+
function highlightFragments(fullText,fragments){
|
| 702 |
+
const ranges=[];
|
| 703 |
+
const uniq=[...new Set(fragments)].filter(f=>f&&f.trim());
|
| 704 |
+
for(const frag of uniq){
|
| 705 |
+
let from=0;
|
| 706 |
+
while(true){
|
| 707 |
+
const idx=fullText.indexOf(frag,from);
|
| 708 |
+
if(idx===-1)break;
|
| 709 |
+
ranges.push([idx,idx+frag.length]);
|
| 710 |
+
from=idx+frag.length;
|
| 711 |
+
}
|
| 712 |
+
}
|
| 713 |
+
return applyRanges(fullText,mergeRanges(ranges));
|
| 714 |
+
}
|
| 715 |
+
function escapeRegExp(s){
|
| 716 |
+
return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");
|
| 717 |
+
}
|
| 718 |
+
function buildWordRegex(term){
|
| 719 |
+
return new RegExp(`(?<![\\p{L}\\p{N}_])${escapeRegExp(term.trim())}(?![\\p{L}\\p{N}_])`,"giu");
|
| 720 |
+
}
|
| 721 |
+
function highlightTerms(fullText,terms){
|
| 722 |
+
const ranges=[];
|
| 723 |
+
for(const term of terms){
|
| 724 |
+
if(!term)continue;
|
| 725 |
+
const re=buildWordRegex(term);
|
| 726 |
+
let m;
|
| 727 |
+
while((m=re.exec(fullText))){
|
| 728 |
+
ranges.push([m.index,m.index+m[0].length]);
|
| 729 |
+
if(m[0].length===0)re.lastIndex++;
|
| 730 |
+
}
|
| 731 |
+
}
|
| 732 |
+
return applyRanges(fullText,mergeRanges(ranges));
|
| 733 |
+
}
|
| 734 |
+
|
| 735 |
+
/* === Панель «Статья целиком» (открывается по клику на крошку) === */
|
| 736 |
+
let matchGroups=[];
|
| 737 |
+
function openArticle(groupId){
|
| 738 |
+
const g=matchGroups[groupId];
|
| 739 |
+
if(!g)return;
|
| 740 |
+
const leaf=bookLeaves[Number(g.leaf)];
|
| 741 |
+
if(!leaf)return;
|
| 742 |
+
const parts=[leaf.book,leaf.section,leaf.article,leaf.subheading].filter(Boolean);
|
| 743 |
+
$("articleTitle").textContent=parts.join(" → ");
|
| 744 |
+
const paragraphs=leaf.text.split("\n").map(p=>p.trim()).filter(Boolean);
|
| 745 |
+
let html="";
|
| 746 |
+
for(const p of paragraphs){
|
| 747 |
+
html+=`<p>${highlightFragments(p,g.fragments)}</p>`;
|
| 748 |
+
}
|
| 749 |
+
$("articleBody").innerHTML=html||`<p class="empty">Текст пуст.</p>`;
|
| 750 |
+
$("articlePanel").style.display="block";
|
| 751 |
+
$("articlePanel").scrollIntoView({behavior:"smooth",block:"start"});
|
| 752 |
+
}
|
| 753 |
+
window.openArticle=openArticle;
|
| 754 |
+
function closeArticle(){
|
| 755 |
+
$("articlePanel").style.display="none";
|
| 756 |
}
|
| 757 |
+
window.closeArticle=closeArticle;
|
| 758 |
|
| 759 |
function showProgress(){
|
| 760 |
$("progressOverlay").style.display="flex";
|
|
|
|
| 869 |
/* ==================== Поиск и отображение результатов ==================== */
|
| 870 |
function renderResults(data,useAdaptive){
|
| 871 |
const out=$("output");
|
| 872 |
+
matchGroups=[];
|
| 873 |
if(data.matched===0){
|
| 874 |
out.className="";
|
| 875 |
out.innerHTML=`<div class="unique-banner">✅ Проверено текстов: ${data.chunks.length}. Совпадений с книгами не найдено.</div>`;
|
|
|
|
| 900 |
groupByLeaf.get(m.article).items.push(m);
|
| 901 |
}
|
| 902 |
for(const g of groups){
|
| 903 |
+
const allFragments=g.items.flatMap(m=>m.fragments||[m.fragment]);
|
| 904 |
+
const groupId=matchGroups.length;
|
| 905 |
+
matchGroups.push({leaf:g.leaf,fragments:allFragments});
|
| 906 |
html+=`<div class="found-item">`;
|
| 907 |
+
html+=`<div class="found-source"><span class="found-label">Найдено в</span> ${leafPath(g.leaf,groupId)}<span class="found-colon">:</span></div>`;
|
| 908 |
g.items.forEach((m,i)=>{
|
| 909 |
html+=`<div class="found-quote${i>0?" found-quote-sep":""}"><span class="pct-badge">${Math.round(m.score)}%</span> — «${escapeHtml(m.fragment)}»</div>`;
|
| 910 |
});
|
|
|
|
| 920 |
if(!chunkRaw.trim()){ alert("Нужно вставить искомый текст."); return; }
|
| 921 |
$("status").textContent="Обработка...";
|
| 922 |
$("run").disabled=true;
|
| 923 |
+
$("articlePanel").style.display="none";
|
| 924 |
showProgress();
|
| 925 |
await new Promise(r=>setTimeout(r,50));
|
| 926 |
try{
|
|
|
|
| 963 |
}
|
| 964 |
}
|
| 965 |
$("run").addEventListener("click",runSearch);
|
| 966 |
+
|
| 967 |
+
/* ==================== Подсчёт слов по статьям ==================== */
|
| 968 |
+
function pluralRaz(n){
|
| 969 |
+
const n10=n%10,n100=n%100;
|
| 970 |
+
if(n100>=11&&n100<=14)return "раз";
|
| 971 |
+
if(n10===1)return "раз";
|
| 972 |
+
if(n10>=2&&n10<=4)return "раза";
|
| 973 |
+
return "раз";
|
| 974 |
+
}
|
| 975 |
+
|
| 976 |
+
function countWordsInBooks(terms){
|
| 977 |
+
// Группируем все листья (в т.ч. подзаголовки) по реальной статье (книга+раздел+статья),
|
| 978 |
+
// чтобы подсчёт был именно "по статьям", а не по каждому подзаголовку отдельно.
|
| 979 |
+
const groups=new Map();
|
| 980 |
+
const order=[];
|
| 981 |
+
for(const leaf of bookLeaves){
|
| 982 |
+
const key=[leaf.book||"",leaf.section||"",leaf.article||""].join("|||");
|
| 983 |
+
if(!groups.has(key)){
|
| 984 |
+
groups.set(key,{book:leaf.book,section:leaf.section,article:leaf.article,text:""});
|
| 985 |
+
order.push(key);
|
| 986 |
+
}
|
| 987 |
+
groups.get(key).text+="\n"+leaf.text;
|
| 988 |
+
}
|
| 989 |
+
const results=[];
|
| 990 |
+
for(const key of order){
|
| 991 |
+
const g=groups.get(key);
|
| 992 |
+
const counts=[];
|
| 993 |
+
for(const term of terms){
|
| 994 |
+
if(!term)continue;
|
| 995 |
+
const re=buildWordRegex(term);
|
| 996 |
+
const c=(g.text.match(re)||[]).length;
|
| 997 |
+
if(c>0)counts.push({term,count:c});
|
| 998 |
+
}
|
| 999 |
+
if(counts.length)results.push({book:g.book,section:g.section,article:g.article,text:g.text,counts});
|
| 1000 |
+
}
|
| 1001 |
+
return results;
|
| 1002 |
+
}
|
| 1003 |
+
|
| 1004 |
+
let wordCountGroups=[];
|
| 1005 |
+
function renderWordCountResults(results,terms){
|
| 1006 |
+
const out=$("output");
|
| 1007 |
+
wordCountGroups=[];
|
| 1008 |
+
if(!results.length){
|
| 1009 |
+
out.className="";
|
| 1010 |
+
out.innerHTML=`<div class="unique-banner">По словам ${terms.map(t=>`«${escapeHtml(t)}»`).join(", ")} совпадений в книгах не найдено.</div>`;
|
| 1011 |
+
return;
|
| 1012 |
+
}
|
| 1013 |
+
let html=`<p>Слов для поиска: <b>${terms.length}</b>. Статей с совпадениями: <b>${results.length}</b>.</p>`;
|
| 1014 |
+
for(const r of results){
|
| 1015 |
+
const groupId=wordCountGroups.length;
|
| 1016 |
+
wordCountGroups.push({book:r.book,section:r.section,article:r.article,text:r.text,terms:r.counts.map(c=>c.term)});
|
| 1017 |
+
const parts=[];
|
| 1018 |
+
if(r.book)parts.push({cls:"crumb-book",text:r.book});
|
| 1019 |
+
if(r.section)parts.push({cls:"crumb-section",text:r.section});
|
| 1020 |
+
if(r.article)parts.push({cls:"crumb-article",text:r.article});
|
| 1021 |
+
const pathHtml=parts.map(p=>`<button type="button" class="crumb ${p.cls}" onclick="openWordCountArticle(${groupId})">${escapeHtml(p.text)}</button>`).join(`<span class="crumb-sep">→</span>`);
|
| 1022 |
+
html+=`<div class="found-item">`;
|
| 1023 |
+
html+=`<div class="found-source">${pathHtml}<span class="found-colon">:</span></div>`;
|
| 1024 |
+
html+=`<ul class="word-count-list">`;
|
| 1025 |
+
for(const c of r.counts){
|
| 1026 |
+
html+=`<li>«<b>${escapeHtml(c.term)}</b>» — ${c.count} ${pluralRaz(c.count)}</li>`;
|
| 1027 |
+
}
|
| 1028 |
+
html+=`</ul>`;
|
| 1029 |
+
html+=`</div>`;
|
| 1030 |
+
}
|
| 1031 |
+
out.className="";
|
| 1032 |
+
out.innerHTML=html;
|
| 1033 |
+
}
|
| 1034 |
+
|
| 1035 |
+
function openWordCountArticle(groupId){
|
| 1036 |
+
const g=wordCountGroups[groupId];
|
| 1037 |
+
if(!g)return;
|
| 1038 |
+
$("articleTitle").textContent=[g.book,g.section,g.article].filter(Boolean).join(" → ");
|
| 1039 |
+
const paragraphs=g.text.split("\n").map(p=>p.trim()).filter(Boolean);
|
| 1040 |
+
let html="";
|
| 1041 |
+
for(const p of paragraphs){
|
| 1042 |
+
html+=`<p>${highlightTerms(p,g.terms)}</p>`;
|
| 1043 |
+
}
|
| 1044 |
+
$("articleBody").innerHTML=html||`<p class="empty">Текст пуст.</p>`;
|
| 1045 |
+
$("articlePanel").style.display="block";
|
| 1046 |
+
$("articlePanel").scrollIntoView({behavior:"smooth",block:"start"});
|
| 1047 |
+
}
|
| 1048 |
+
window.openWordCountArticle=openWordCountArticle;
|
| 1049 |
+
|
| 1050 |
+
async function runWordCount(){
|
| 1051 |
+
const raw=$("chunksText").value.trim();
|
| 1052 |
+
if(!raw){ alert("Введите слова через запятую, например: Мария, зачатие"); return; }
|
| 1053 |
+
const terms=raw.split(",").map(t=>t.trim()).filter(Boolean);
|
| 1054 |
+
if(!terms.length){ alert("Не удалось распознать ни одного слова."); return; }
|
| 1055 |
+
$("status").textContent="Обработка...";
|
| 1056 |
+
$("run").disabled=true;
|
| 1057 |
+
$("countWords").disabled=true;
|
| 1058 |
+
$("articlePanel").style.display="none";
|
| 1059 |
+
showProgress();
|
| 1060 |
+
await new Promise(r=>setTimeout(r,50));
|
| 1061 |
+
try{
|
| 1062 |
+
updateProgress(0,1,"Загрузка книг...");
|
| 1063 |
+
await loadBooksData();
|
| 1064 |
+
if(booksLoadError){
|
| 1065 |
+
$("output").className="";
|
| 1066 |
+
$("output").innerHTML=`<div class="book-match-error">⚠️ ${escapeHtml(booksLoadError)}</div>`;
|
| 1067 |
+
$("status").textContent="Ошибка загрузки книг";
|
| 1068 |
+
return;
|
| 1069 |
+
}
|
| 1070 |
+
updateProgress(1,1,"Подсчёт слов...");
|
| 1071 |
+
const results=countWordsInBooks(terms);
|
| 1072 |
+
renderWordCountResults(results,terms);
|
| 1073 |
+
$("status").textContent=`Готово: слов — ${terms.length}, статей с совпадениями — ${results.length}.`;
|
| 1074 |
+
}catch(e){
|
| 1075 |
+
console.error(e);
|
| 1076 |
+
$("status").textContent="Ошибка";
|
| 1077 |
+
$("output").className="";
|
| 1078 |
+
$("output").innerHTML=`<div class="empty">Ошибка: ${escapeHtml(e.message)}</div>`;
|
| 1079 |
+
}finally{
|
| 1080 |
+
hideProgress();
|
| 1081 |
+
$("run").disabled=false;
|
| 1082 |
+
$("countWords").disabled=false;
|
| 1083 |
+
}
|
| 1084 |
+
}
|
| 1085 |
+
$("countWords").addEventListener("click",runWordCount);
|
| 1086 |
</script>
|
| 1087 |
</body>
|
| 1088 |
</html>
|