Skip to content

Commit

Permalink
mundaneum: Add highlight
Browse files Browse the repository at this point in the history
Signed-off-by: Patrick José Pereira <patrickelectric@gmail.com>
  • Loading branch information
patrickelectric committed Apr 22, 2024
1 parent 4470324 commit 4110b9c
Showing 1 changed file with 27 additions and 8 deletions.
35 changes: 27 additions & 8 deletions static/mundaneum/index.html
Expand Up @@ -42,6 +42,11 @@
font-size: 20px;
margin-top: 20px;
}

.highlight {
background-color: yellow;
color: black;
}
</style>
</head>
<body>
Expand All @@ -53,7 +58,7 @@
<script src="https://cdn.jsdelivr.net/npm/fuse.js/dist/fuse.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
fetch('post-its.md')
fetch('/mundaneum/post-its.md')
.then(response => {
if (!response.ok) {
throw new Error('Failed to load the markdown file');
Expand All @@ -75,27 +80,41 @@
const fuse = new Fuse(posts, {
includeScore: true,
includeMatches: true,
findAllMatches: true,
findAllMatches: false,
shouldSort: true,
threshold: 0.4,
threshold: 0.3,
ignoreLocation: true,
minMatchCharLength: 2,
fieldNormWeight: 0.01,
});
const searchInput = document.getElementById('search');
const container = document.getElementById('postit-container');

searchInput.addEventListener('input', function() {
const results = searchInput.value ? fuse.search(searchInput.value) : posts.map(post => ({ item: post }));
console.log(results)
displayPosts(results.map(result => result.item));
displayPostsSearch(results);
});

displayPosts(posts); // display all posts initially

displayPosts(posts); // display all posts initially
function displayPosts(posts) {
container.innerHTML = posts.map(post => `<div class="post-it">${post.replace(/\n/g, '<br>')}</div>`).join('');
}

function displayPostsSearch(results) {
container.innerHTML = results.map(result => {
let highlightedText = result.item;
if (result.matches && result.matches.length > 0) {
// Find the largest match
const largestMatch = result.matches[0].indices.reduce((largest, current) => {
return (current[1] - current[0] > largest[1] - largest[0]) ? current : largest;
}, [0, 0]);
// Highlight the largest match
highlightedText = `${highlightedText.substring(0, largestMatch[0])}` +
`<span class="highlight">${highlightedText.substring(largestMatch[0], largestMatch[1] + 1)}</span>` +
`${highlightedText.substring(largestMatch[1] + 1)}`;
}
return `<div class="post-it">${highlightedText.replace(/\n/g, '<br>')}</div>`;
}).join('');
}
}
});
</script>
Expand Down

0 comments on commit 4110b9c

Please sign in to comment.