Skip to content

Commit

Permalink
feat: add full text search document for html.
Browse files Browse the repository at this point in the history
  • Loading branch information
auula committed Jul 16, 2024
1 parent e26acfc commit 8a1b9ba
Show file tree
Hide file tree
Showing 6 changed files with 76 additions and 88 deletions.
4 changes: 1 addition & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,4 @@ This project follows the all-contributors specification. All kinds of contributi

> 中国大陆用户可以加微信群一起讨论设计与代码实现细节。

<img src="https://github.com/auula/typikon/assets/38412458/1eac857f-0309-404d-a8f9-f92dd1606677" alt="Alt text" style="width: 180px; height: 260px;">


<img src="https://img.ibyte.me/nlbxzp.jpg" alt="Alt text" style="width: 180px; height: 260px;">
12 changes: 6 additions & 6 deletions src/book/builder.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use tera::{Context, Tera};

use crate::{
book::data::Document,
book::search::Document,
cli,
html::{self, Hypertext, Markdown, Template},
utils::{self, Logger},
Expand Down Expand Up @@ -146,10 +146,10 @@ impl Builder {

// push full text search data
self.document_index += 1;
let _ = &mut self.search_data.push(Document::new(
self.search_data.push(Document::new(
self.document_index,
"/index.html".to_string(),
template.name,
template.name.clone(),
hypertext.to_html(),
));

Expand Down Expand Up @@ -206,7 +206,7 @@ impl Builder {

// push full text search data
self.document_index += 1;
let _ = &mut self.search_data.push(Document::new(
self.search_data.push(Document::new(
self.document_index,
format!(
"/{}/{}.html",
Expand Down Expand Up @@ -267,7 +267,7 @@ impl Builder {

// push full text search data
self.document_index += 1;
let _ = &mut self.search_data.push(Document::new(
self.search_data.push(Document::new(
self.document_index,
format!(
"/{}/index.html",
Expand Down Expand Up @@ -324,7 +324,7 @@ impl Builder {
chapter_path
));
}
Err(_) => continue,
Err(_) => log.error(format_args!("file not found {:?}", &chapter_path)),
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/book/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
pub mod builder;
pub mod root;
pub mod data;
pub mod search;
pub mod settings;

pub use builder::*;
pub use root::*;
pub use data::*;
pub use search::*;
pub use settings::*;
File renamed without changes.
2 changes: 1 addition & 1 deletion src/utils/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ pub fn remove_md_extension(filename: &str) -> String {
}

pub fn download_zip() -> Result<(), Box<dyn std::error::Error>> {
let repo_url = "https://github.com/typikonbook/typikon-book/archive/refs/heads/main.zip";
let repo_url = "https://github.com/typikonbook/typikon-book-v3/archive/refs/heads/main.zip";
let zip_path = Path::new("repo.zip");
let extract_path = Path::new(".");

Expand Down
142 changes: 66 additions & 76 deletions theme/typikon-theme/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,11 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>{{ title }}</title>
<meta name="description" content="{{ description }}" />
<meta name="keywords" content="{{ keywords }}" />
<meta name="generator" content="typikon" />
<meta name="template" content="typikon-theme" />
<meta name="description" content="{{ description }}">
<meta name="keywords" content="{{ keywords }}">
<meta name="generator" content="typikon">
<meta name="template" content="typikon-theme">

{% for css_path in custom_css %}
<link rel="stylesheet" href="{{ css_path | safe }}">
Expand All @@ -20,7 +19,6 @@
<link rel="stylesheet" href="/assets/dark-theme.css" id="dark-theme" disabled>

<link rel="icon" href="{{ icon | safe }}" type="image/png">

</head>

<body>
Expand All @@ -41,7 +39,7 @@
</path>
</svg>
</span>
<input type="text" class="form-control" id="serach-text" placeholder="Full text serach..."
<input type="text" class="form-control" id="search-text" placeholder="Full text search..."
aria-describedby="basic-addon1">
</div>
<ul class="list-unstyled ps-0" id="chapterList">
Expand Down Expand Up @@ -90,36 +88,29 @@
{% endfor %}

<script>
document.addEventListener('DOMContentLoaded', initTheme);
window.onload = () => {
themeChange();
fullTextSearch();
};
document.addEventListener('DOMContentLoaded', function () {
initTheme();
initializeSearch();
});

function initTheme(event) {
function initTheme() {
const darkThemeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
const lightThemeLink = document.getElementById('light-theme');
const darkThemeLink = document.getElementById('dark-theme');

changeTheme = (mediaQuery) => {
const changeTheme = (mediaQuery) => {
if (mediaQuery.matches) {
// Dark mode
lightThemeLink.setAttribute('disabled', true);
darkThemeLink.removeAttribute('disabled');
} else {
// Light mode
darkThemeLink.setAttribute('disabled', true);
lightThemeLink.removeAttribute('disabled');
}
};

// Initial check
changeTheme(darkThemeMediaQuery);

// Listen for changes in OS theme
darkThemeMediaQuery.addListener(changeTheme);

// Initial highlight.js
document.querySelectorAll('pre code').forEach((block) => {
hljs.highlightElement(block);
});
Expand All @@ -131,62 +122,61 @@
paragraph.classList.add('md-p');
});
}
};

function fullTextSearch() {
// Full text search data
const data = [
{ id: '1', title: '示例文档一', content: '这是示例文档一的内容。' },
{ id: '2', title: '示例文档二', content: '这是示例文档二的内容。' }
];

// Fuse.js options
const options = {
keys: ['title', 'content'],
includeScore: true,
tokenize: true,
threshold: 0.3,
tokenSeparator: /[,|,|。]/
};

const fuse = new Fuse(data, options);
const chapterList = document.getElementById('chapterList');

function performSearch() {
const query = document.getElementById('serach-text').value.trim();
const results = fuse.search(query);

chapterList.style.display = query !== '' ? 'none' : 'block';

results.forEach(result => {
console.log(`${result.item.title} - ${result.item.content}`);
});
};

const searchInput = document.getElementById("serach-text");
searchInput.addEventListener("input", performSearch);
};

function themeChange() {
const darkThemeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
const lightThemeLink = document.getElementById('light-theme');
const darkThemeLink = document.getElementById('dark-theme');
changeTheme = (mediaQuery) => {
if (mediaQuery.matches) {
// Dark mode
lightThemeLink.setAttribute('disabled', true);
darkThemeLink.removeAttribute('disabled');
} else {
// Light mode
darkThemeLink.setAttribute('disabled', true);
lightThemeLink.removeAttribute('disabled');
}
};
// Initial check
changeTheme(darkThemeMediaQuery);
// Listen for changes in OS theme
darkThemeMediaQuery.addListener(changeTheme);
};
}

function initializeSearch() {
fetch('/data.json')
.then(response => response.json())
.then(data => {
const options = {
keys: ['title', "content"],
includeScore: true,
tokenize: true,
threshold: 0.3,
tokenSeparator: /[,|,|。]/
};

const fuse = new Fuse(data, options);
const chapterList = document.getElementById('chapterList');
// 复制一份复原使用
let innerHTML = chapterList.innerHTML;
function performSearch() {
const query = document.getElementById('search-text').value.trim();
const results = fuse.search(query);

// 设置显示菜单和搜索结果,如果没有搜索结果就显示菜单,有则反之
chapterList.innerHTML = results.length <= 0 ? chapterList.innerHTML = innerHTML : '';

// 遍历搜索结果并生成对应的 HTML
results.forEach(result => {
const sub_chapter = result.item; // 假设每个搜索结果是 sub_chapter 对象

// 构建章节和子章节的列表项 HTML
const listItem = `
<li class="mb-1">
<div class="collapse show" id="collapse1">
<ul class="btn-toggle-nav list-unstyled fw-normal pb-1 small">
<li>
<a href="${sub_chapter.url}"
class="link-body-emphasis d-inline-flex text-decoration-none rounded">
${sub_chapter.title}
</a>
</li>
</ul>
</div>
</li>
`;

// 将拼接好的章节列表项添加到章节列表容器
chapterList.innerHTML += listItem;
});
}

const searchInput = document.getElementById('search-text');
searchInput.addEventListener('input', performSearch);
})
.catch(error => console.error('Error fetching data:', error));
}
</script>
</body>

Expand Down

0 comments on commit 8a1b9ba

Please sign in to comment.